0% found this document useful (0 votes)
8 views

Question Paper 4 Java

Uploaded by

mohanraj08052006
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Question Paper 4 Java

Uploaded by

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

QUESTION PAPER 4

PART A (10 x 2 = 20):

1. Java Language is Platform Independent. Justify your answer.


Java is platform-independent because the Java Compiler converts the source code into
bytecode, which is a platform-neutral intermediate form. This bytecode is executed by
the Java Virtual Machine (JVM), which is available on various platforms. Thus, Java
follows the principle of "Write Once, Run Anywhere (WORA)."

Example: A .class file compiled on Windows can run on Linux or Mac if the JVM is
installed.

2. Difference between Method and Constructor:


o Method:
 A block of code that performs a specific task.
 Can have any name.
 Explicitly called by the programmer.
o Constructor:
 A special method used to initialize objects.
 Must have the same name as the class.
 Automatically invoked when an object is created.
Example:

class Demo {
Demo() { // Constructor
System.out.println("Constructor called!");
}
void display() { // Method
System.out.println("Method called!");
}
}

3. Differentiate Method Overloading and Overriding:


o Method Overloading:
 Defined in the same class with the same name but different parameter
lists.
 Achieved at compile time.
o Method Overriding:
 Defined in a subclass to modify the behavior of a method in the parent
class.
 Achieved at runtime.

Example:

class Parent {
void show() { System.out.println("Parent Method"); }
}
class Child extends Parent {
void show() { System.out.println("Child Method"); } // Overriding
}

4. Can We Access Parent Class Variables in Child Class by Using super Keyword?
Yes, the super keyword allows access to variables, methods, and constructors of the
parent class.
Example:

class Parent {
int num = 100;
}
class Child extends Parent {
void display() {
System.out.println("Parent's num: " + super.num);
}
}

5. Define Arithmetic Exception with Example:


An ArithmeticException occurs when there is an illegal arithmetic operation, such as
division by zero.
Example:

public class ArithmeticExceptionExample {


public static void main(String[] args) {
try {
int result = 10 / 0; // Throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("ArithmeticException: " +
e.getMessage());
}
}
}

6. Name the Two Ways to Create a Thread in Java:


1. Extending the Thread class:
A class can inherit the Thread class and override its run() method.
Example:

class MyThread extends Thread {


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

2. Implementing the Runnable interface:


A class implements the Runnable interface and defines the run() method.
Example:

class MyRunnable implements Runnable {


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

7. What is Thread Pool?


A Thread Pool is a collection of reusable threads that execute tasks efficiently. Instead
of creating new threads for every task, threads are reused from the pool, reducing
overhead and improving performance. It is managed by the Executor framework.

Example:

ExecutorService executor = Executors.newFixedThreadPool(5);


executor.submit(() -> System.out.println("Task executed"));

8. When Must a Class Be Declared as Abstract?


A class must be declared abstract when:
o It has at least one abstract method (method without implementation).
o It is meant to serve as a base class for inheritance.

Example:

abstract class Shape {


abstract void draw(); // Abstract method
}
class Circle extends Shape {
void draw() { System.out.println("Drawing Circle"); }
}
9. What is a Layout Manager and Its Types in Java AWT?
A Layout Manager in Java AWT is used to arrange components within a container. It
simplifies the process of aligning and positioning GUI elements.
Types:
o FlowLayout: Arranges components in a row, wrapping to the next row if needed.
o BorderLayout: Divides the container into North, South, East, West, and Center
regions.
o GridLayout: Arranges components in a grid of equal-sized cells.
o CardLayout: Manages multiple panels, one visible at a time.
o GridBagLayout: Flexible layout with control over component alignment and
size.

10. Differentiate HBox and VBox:


o HBox:
 Arranges components horizontally in a single row.
 Used for aligning elements side by side.
o VBox:
 Arranges components vertically in a single column.
 Used for stacking elements one below the other.

Example:

HBox hbox = new HBox(new Button("Button 1"), new Button("Button 2"));


VBox vbox = new VBox(new Button("Button 1"), new Button("Button 2"));

Part B – (5 × 13 = 65 marks)

11.

(a) (i) Differentiate between Object-Oriented Programming (OOP) and Procedure-Oriented


Programming (POP). (7 marks)

Introduction to OOP and POP

Programming paradigms play a key role in structuring and organizing code. Two major
programming paradigms are Object-Oriented Programming (OOP) and Procedure-Oriented
Programming (POP).

Object-Oriented Programming (OOP) focuses on data and methods, encapsulated into objects.
It emphasizes real-world modeling, making it easier to manage and maintain large codebases.
Procedure-Oriented Programming (POP) focuses on a sequence of actions
(functions/procedures) to be executed in a specific order.

Comparison Table: OOP vs POP

Procedure-Oriented Programming
Feature Object-Oriented Programming (OOP)
(POP)

Focuses on objects (data and functions Focuses on functions (procedures) that


Focus
together). operate on data.

Data and functions are encapsulated into Data is separate from functions and
Data Encapsulation
classes and objects. passed between them.

High, through inheritance and


Reusability Low, as code tends to be repeated.
polymorphism.

Lower, as the program is a linear


Modularity High, due to modular class-based design.
sequence of function calls.

Top-down design using classes and


Approach Bottom-up design using functions.
objects.

Example Paradigms Java, Python, C++, C#, etc. C, Fortran, Assembly, etc.

Real-World Better representation of real-world


Less intuitive for real-world mapping.
Representation entities as objects.

11. (a) (ii)

Java Program to Find the Greatest of Three Numbers. (6 marks)

Problem: Write a Java program to find the greatest of three numbers.

Solution: The program will take three numbers as input, compare them, and display the greatest
one.

import java.util.Scanner;

public class GreatestNumber {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = sc.nextInt();
System.out.print("Enter second number: ");
int num2 = sc.nextInt();
System.out.print("Enter third number: ");
int num3 = sc.nextInt();

int greatest = num1;

if (num2 > greatest) {


greatest = num2;
}
if (num3 > greatest) {
greatest = num3;
}

System.out.println("The greatest number is: " + greatest);


}
}

Output:

Enter first number: 10


Enter second number: 20
Enter third number: 30
The greatest number is: 30

11. (b) (i) Explain Constructor with an Example (6 marks)

What is a Constructor?

A constructor in Java is a special method used to initialize objects. It is invoked at the time of
object creation and does not have a return type, not even void.

 Types of Constructors:
1. Default Constructor - Provides default values.
2. Parameterized Constructor - Initializes objects with specific values.

Example: Constructor in Java

class Student {
String name;
int age;

// Parameterized Constructor
Student(String n, int a) {
name = n;
age = a;
}

// Method to display student details


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

public class Main {


public static void main(String[] args) {
// Creating an object using parameterized constructor
Student student1 = new Student("John", 20);
student1.display();
}
}

Output:

Name: John
Age: 20

11. (b) (ii) Java Program to Display the Grade of Students Using get(), compute(), and display()
Methods. (7 marks)

Problem: Write a program to input student marks using the get() method, calculate the average
using compute() method, and display the grade using display() method.

import java.util.Scanner;

class Student {
private int marks1, marks2, marks3;

// Method to get marks from the user


void get() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter marks for Subject 1: ");
marks1 = sc.nextInt();
System.out.print("Enter marks for Subject 2: ");
marks2 = sc.nextInt();
System.out.print("Enter marks for Subject 3: ");
marks3 = sc.nextInt();
}

// Method to compute the average marks


double compute() {
return (marks1 + marks2 + marks3) / 3.0;
}

// Method to display the grade


void display() {
double average = compute();
System.out.println("Average Marks: " + average);
if (average >= 90) {
System.out.println("Grade: A");
} else if (average >= 75) {
System.out.println("Grade: B");
} else if (average >= 60) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: D");
}
}
}

public class Main {


public static void main(String[] args) {
Student student = new Student();
student.get();
student.display();
}
}

Output:

Enter marks for Subject 1: 85


Enter marks for Subject 2: 90
Enter marks for Subject 3: 80
Average Marks: 85.0
Grade: B

12. (a) (i)

Java Program for Library Interface with drawBook(), returnBook(), and checkStatus()
Methods. (8 marks)

Problem: Create an interface to manage library operations like drawing a book, returning a
book, and checking the status.

interface Library {
void drawBook();
void returnBook();
void checkStatus();
}

class LibrarySystem implements Library {


private int availableBooks = 5;

@Override
public void drawBook() {
if (availableBooks > 0) {
availableBooks--;
System.out.println("Book drawn. Remaining books: " +
availableBooks);
} else {
System.out.println("No books available.");
}
}

@Override
public void returnBook() {
availableBooks++;
System.out.println("Book returned. Available books: " +
availableBooks);
}

@Override
public void checkStatus() {
System.out.println("Books available: " + availableBooks);
}
}

public class Main {


public static void main(String[] args) {
Library library = new LibrarySystem();
library.checkStatus();
library.drawBook();
library.checkStatus();
library.returnBook();
library.checkStatus();
}
}

Output:

Books available: 5
Book drawn. Remaining books: 4
Books available: 4
Book returned. Available books: 5
Books available: 5

12. (a) (ii) Explain Method Overloading with an Example. (5 marks)

What is Method Overloading?

Method overloading is a feature in Java where multiple methods can have the same name but
differ in the number or type of parameters. It allows methods to perform similar tasks but with
different inputs.

Example: Method Overloading:


class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}

// Method to add three integers


int add(int a, int b, int c) {
return a + b + c;
}
}

public class Main {


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

Output:

Sum of 2 numbers: 15
Sum of 3 numbers: 30

13. (a)

Create Software for Departmental Stores to Maintain the Following Details: Item Number, Item
Description, Requested Quantity, and Cost Price. Provide the Options to Update the Stock.
Calculate the Selling Price (SP = CP * 20%). Create an Exception Whenever the Selling Price of
an Item Exceeds the Given Amount. (13 marks)

Introduction

In a departmental store, it is essential to maintain stock and calculate the selling price of each
item based on the cost price (CP). The selling price (SP) is calculated by adding a 20% markup
on the cost price. We will also create an exception when the selling price exceeds a certain
threshold.

Class Design

We will create the following:

1. Item Class: This will hold the details of each item, including item number, description, cost price,
and quantity.
2. Store Class: This will manage the store's stock and update it, calculating the selling price.
3. Custom Exception: To handle cases where the selling price exceeds a given amount.

Java Program Implementation


java
Copy code
// Custom Exception Class
class PriceExceededException extends Exception {
public PriceExceededException(String message) {
super(message);
}
}

class Item {
int itemNo;
String itemDescription;
int quantity;
double costPrice;

// Constructor to initialize item details


Item(int itemNo, String itemDescription, int quantity, double costPrice) {
this.itemNo = itemNo;
this.itemDescription = itemDescription;
this.quantity = quantity;
this.costPrice = costPrice;
}

// Method to calculate selling price


double calculateSellingPrice() {
return costPrice + (costPrice * 0.20);
}

// Method to check if the selling price exceeds a certain threshold


void checkPrice(double threshold) throws PriceExceededException {
if (calculateSellingPrice() > threshold) {
throw new PriceExceededException("Selling price of item exceeds
threshold!");
}
}
}

class Store {
Item[] items;

// Constructor to initialize items in the store


Store(Item[] items) {
this.items = items;
}

// Method to update the stock


void updateStock(int itemNo, int quantity) {
for (Item item : items) {
if (item.itemNo == itemNo) {
item.quantity += quantity;
System.out.println("Stock updated. New quantity of item " +
itemNo + ": " + item.quantity);
return;
}
}
System.out.println("Item not found!");
}

// Method to display item details and check selling price


void displayItemDetails(double threshold) {
for (Item item : items) {
try {
item.checkPrice(threshold);
System.out.println("Item Number: " + item.itemNo);
System.out.println("Description: " + item.itemDescription);
System.out.println("Quantity: " + item.quantity);
System.out.println("Cost Price: " + item.costPrice);
System.out.println("Selling Price: " +
item.calculateSellingPrice());
System.out.println("------------------------");
} catch (PriceExceededException e) {
System.out.println(e.getMessage());
}
}
}
}

public class Main {


public static void main(String[] args) {
// Create some sample items
Item item1 = new Item(101, "Laptop", 10, 50000);
Item item2 = new Item(102, "Phone", 20, 15000);
Item item3 = new Item(103, "Tablet", 30, 20000);

Item[] items = {item1, item2, item3};

// Create store object


Store store = new Store(items);

// Update stock
store.updateStock(102, 5);

// Display item details and check price


store.displayItemDetails(25000); // Set a threshold for selling price
}
}

Explanation:

1. PriceExceededException: Custom exception to handle cases where the selling price exceeds the
threshold.
2. Item Class: Stores item details and provides methods to calculate the selling price and check if
the price exceeds the threshold.
3. Store Class: Manages an array of items, updates stock, and displays item details.
4. Main Class: Contains the main method to test the functionality.

Output:

Stock updated. New quantity of item 102: 25


Item Number: 101
Description: Laptop
Quantity: 10
Cost Price: 50000.0
Selling Price: 60000.0
------------------------
Item Number: 102
Description: Phone
Quantity: 25
Cost Price: 15000.0
Selling Price: 18000.0
------------------------
Item Number: 103
Description: Tablet
Quantity: 30
Cost Price: 20000.0
Selling Price: 24000.0
------------------------

Exception Output (if SP exceeds threshold):

Selling price of item exceeds threshold!

13. (b) (i)

Discuss About Try, Catch, and Finally Keywords in Exception Handling with an Example. (8
marks)

Introduction to Exception Handling in Java

Java provides a robust mechanism to handle runtime errors via exception handling. The primary
keywords used are try, catch, and finally. Exception handling allows Java programs to
handle unexpected errors without crashing.

Explanation of Keywords
 try: The try block contains code that might throw an exception. It is followed by one or more
catch blocks that handle the exception if thrown.
 catch: The catch block is used to handle the exception. It catches specific types of exceptions
thrown in the try block.
 finally: The finally block contains code that will execute regardless of whether an
exception is thrown or not. It is used to close resources (like files or network connections).

Example: Try, Catch, and Finally:


public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
} finally {
System.out.println("This block is always executed.");
}
}
}

Explanation:

 try: The code that may throw an exception (division by zero).


 catch: Catches the ArithmeticException and prints an error message.
 finally: The message in the finally block is always printed, regardless of whether an
exception occurred or not.

Output:

Error: Division by zero is not allowed.


This block is always executed.

13. (b) (ii) List and Explain Data Types and Their Corresponding Wrapper Classes. (5 marks)

Primitive Data Types and Their Corresponding Wrapper Classes

In Java, primitive data types are the building blocks for data manipulation. Each primitive data
type has a corresponding wrapper class that provides methods to convert between primitive
values and objects.
Primitive Type Wrapper Class Description

Byte Byte Holds an 8-bit signed integer.

short Short Holds a 16-bit signed integer.

int Integer Holds a 32-bit signed integer.

long Long Holds a 64-bit signed integer.

float Float Holds a 32-bit floating point number.

double Double Holds a 64-bit floating point number.

char Character Holds a single 16-bit Unicode character.

boolean Boolean Holds a true or false value.

Example:

public class WrapperExample {


public static void main(String[] args) {
// Using Wrapper Classes
Integer intValue = 100; // Integer object
Double doubleValue = 15.5; // Double object

// Unboxing (converting from Wrapper to Primitive)


int primitiveInt = intValue; // Unboxing
double primitiveDouble = doubleValue; // Unboxing

// Display values
System.out.println("Integer value: " + intValue);
System.out.println("Double value: " + doubleValue);
System.out.println("Unboxed Integer: " + primitiveInt);
System.out.println("Unboxed Double: " + primitiveDouble);
}
}

Output:

Integer value: 100


Double value: 15.5
Unboxed Integer: 100
Unboxed Double: 15.5

14. (a) (i) Explain StringBuffer Class with Example. (6 marks)


Introduction to StringBuffer

In Java, StringBuffer is a mutable sequence of characters. Unlike the String class, which
creates a new object for each modification, StringBuffer allows for efficient modification of
strings without creating multiple objects, which makes it more suitable for heavy string
manipulations.

Key Features of StringBuffer:

1. Mutable: Unlike String, StringBuffer allows modification of the string without creating a new
object.
2. Thread-Safe: StringBuffer is synchronized, meaning it is thread-safe. However, it can be slower
compared to StringBuilder because of synchronization.
3. Capacity: StringBuffer maintains a capacity to store characters. If the number of characters
exceeds the capacity, the buffer is automatically resized.

Common Methods of StringBuffer:

1. append(String str): Adds the given string to the end of the current string buffer.
2. insert(int offset, String str): Inserts a given string at a specified index.
3. delete(int start, int end): Deletes the characters between the given indices.
4. reverse(): Reverses the characters in the buffer.

Example Program

public class StringBufferExample {


public static void main(String[] args) {
// Creating a StringBuffer object
StringBuffer sb = new StringBuffer("Hello");

// Appending a string to StringBuffer


sb.append(" World");
System.out.println("After append: " + sb);

// Inserting a string at a specific position


sb.insert(5, ",");
System.out.println("After insert: " + sb);

// Reversing the StringBuffer


sb.reverse();
System.out.println("After reverse: " + sb);

// Deleting a part of the string


sb.delete(0, 6);
System.out.println("After delete: " + sb);
}
}

Output:

After append: Hello World


After insert: Hello, World
After reverse: dlroW ,olleH
After delete: ,olleH

14. (a) (ii) Outline Parameter Type Bounds with an Example. (7 marks)

Introduction to Parameter Type Bounds in Java

In Java, parameterized types are used with generics to create classes, interfaces, and methods that
operate on objects of various types while providing compile-time type safety. Type bounds are
used in generics to restrict the types that can be passed as arguments to a generic class, interface,
or method.

Types of Bounds:

1. Upper Bound: Restricts the type to be a specific class or its subclasses. This is done using the
extends keyword.
2. Lower Bound: Restricts the type to be a specific class or its superclasses. This is done using the
super keyword.

Upper Bound Example:

The upper bound restricts the type to be the specified class or its subclass.

// A method that accepts a list of numbers (only Integer or its subclass)


public class UpperBoundExample {
public static <T extends Number> void printNumbers(T number) {
System.out.println(number);
}

public static void main(String[] args) {


printNumbers(100); // Integer
printNumbers(12.5); // Double
}
}

Output:

Copy code
100
12.5

In this case, T extends Number ensures that the method can accept objects of type Number or
any subclass (like Integer, Double).

Lower Bound Example:

The lower bound restricts the type to be the specified class or its superclasses.

// A method that accepts a list of numbers (any class that is a superclass of


Integer)
public class LowerBoundExample {
public static void addNumbers(List<? super Integer> list) {
list.add(10); // Integer is added to a list that could hold Integer or
its superclasses
}

public static void main(String[] args) {


List<Number> numberList = new ArrayList<>();
addNumbers(numberList);
System.out.println(numberList);
}
}

Output:

csharp
Copy code
[10]

In this example, List<? super Integer> allows the list to accept Integer and any class that is
a superclass of Integer (such as Number or Object).

15. (a) (i) List and Explain the Various Layouts in Java GUI. (8 marks)
Introduction to Layouts in Java GUI

In Java, the Swing package provides several layout managers to manage the placement and
sizing of components in a container. A layout manager is an object that controls the positioning
and size of components within a container.

Common Layout Managers:

1. FlowLayout:
o Components are arranged in a left-to-right flow, similar to how text is arranged in a
paragraph.
o The default alignment is centered, but it can be changed.

2. BorderLayout:
o Divides the container into five regions: North, South, East, West, and Center.
o Each region can hold one component, and components stretch to fill the available space
in each region.

3. GridLayout:
o Arranges components in a grid of rows and columns, with equal-sized cells.
o It’s useful when you need to align components in a grid.

4. GridBagLayout:
o Allows for more flexible grid-based layouts than GridLayout.
o Components can span multiple rows or columns.

5. BoxLayout:
o Arranges components either vertically or horizontally.
o It is often used for forms and menus.

6. CardLayout:
o Manages components like a stack of cards. Only one card is visible at a time.
o Useful for implementing tabbed panels or wizards.

7. AbsoluteLayout:
o No layout manager; components are positioned using specific coordinates.
o Should be avoided in most cases since it doesn't scale well across different screen sizes.

Example of Using FlowLayout:


import javax.swing.*;
import java.awt.*;

public class LayoutExample {


public static void main(String[] args) {
JFrame frame = new JFrame("FlowLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());

// Add buttons
frame.add(new JButton("Button 1"));
frame.add(new JButton("Button 2"));
frame.add(new JButton("Button 3"));

frame.setSize(300, 200);
frame.setVisible(true);
}
}

15. (a) (ii) Explain the Four Types of Buttons in Swing. (5 marks)

Swing Buttons Types:

1. JButton: Standard button used for actions such as submitting a form or triggering an
event.

JButton button = new JButton("Click Me");

2. JCheckBox: Allows the user to select or deselect a choice. It can be checked or


unchecked.

JCheckBox checkBox = new JCheckBox("Accept Terms and Conditions");

3. JRadioButton: A button that allows users to choose only one option from a set of
options.

JRadioButton radioButton1 = new JRadioButton("Option 1");

4. JToggleButton: A button that can be toggled on or off. Similar to a checkbox but looks
like a button.

JToggleButton toggleButton = new JToggleButton("On/Off");


15. (b) Discuss the Following with Example:

(i) Mouse Listener (7 marks)

Introduction to MouseListener in Java

In Java, the MouseListener interface is used to handle mouse events. This interface is a part of
the java.awt.event package and provides methods to respond to mouse actions such as
clicking, pressing, releasing, entering, and exiting a component. The methods of the
MouseListener interface must be implemented in a class that listens for mouse events.

Methods of MouseListener:

1. mouseClicked(MouseEvent e): Invoked when the mouse button is clicked (pressed and
released) on a component.
2. mousePressed(MouseEvent e): Invoked when a mouse button is pressed on a component.
3. mouseReleased(MouseEvent e): Invoked when a mouse button is released on a component.
4. mouseEntered(MouseEvent e): Invoked when the mouse enters a component.
5. mouseExited(MouseEvent e): Invoked when the mouse exits a component.

Example Program Using MouseListener

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

public class MouseListenerExample extends Frame implements MouseListener {

public MouseListenerExample() {
// Set up the frame
setTitle("MouseListener Example");
setSize(400, 300);
addMouseListener(this); // Adding MouseListener to the frame
setVisible(true);
}

// Implement the MouseListener methods


public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at (" + e.getX() + ", " + e.getY() +
")");
}
public void mousePressed(MouseEvent e) {
System.out.println("Mouse pressed at (" + e.getX() + ", " + e.getY() +
")");
}

public void mouseReleased(MouseEvent e) {


System.out.println("Mouse released at (" + e.getX() + ", " + e.getY()
+ ")");
}

public void mouseEntered(MouseEvent e) {


System.out.println("Mouse entered the window");
}

public void mouseExited(MouseEvent e) {


System.out.println("Mouse exited the window");
}

public static void main(String[] args) {


new MouseListenerExample();
}
}

Output:
arduino
Copy code
Mouse entered the window
Mouse clicked at (200, 150)
Mouse released at (200, 150)
Mouse exited the window

In this example, a window is created and the MouseListener methods print messages when the
mouse enters, clicks, releases, or exits the window.

(ii) Mouse Motion Listener (7 marks)

Introduction to MouseMotionListener in Java

The MouseMotionListener interface is used to listen for mouse motion events, such as when the
mouse moves within a component. Unlike MouseListener, which responds to mouse button
events, MouseMotionListener responds to mouse movement.

Methods of MouseMotionListener:

1. mouseMoved(MouseEvent e): Invoked when the mouse is moved over a component.


2. mouseDragged(MouseEvent e): Invoked when the mouse is moved while a mouse button is
pressed.

Example Program Using MouseMotionListener


java
Copy code
import java.awt.*;
import java.awt.event.*;

public class MouseMotionListenerExample extends Frame implements


MouseMotionListener {

public MouseMotionListenerExample() {
// Set up the frame
setTitle("MouseMotionListener Example");
setSize(400, 300);
addMouseMotionListener(this); // Adding MouseMotionListener to the
frame
setVisible(true);
}

// Implement the MouseMotionListener methods


public void mouseMoved(MouseEvent e) {
System.out.println("Mouse moved at (" + e.getX() + ", " + e.getY() +
")");
}

public void mouseDragged(MouseEvent e) {


System.out.println("Mouse dragged at (" + e.getX() + ", " + e.getY() +
")");
}

public static void main(String[] args) {


new MouseMotionListenerExample();
}
}

Output:
arduino
Copy code
Mouse moved at (200, 150)
Mouse moved at (205, 160)
Mouse dragged at (210, 170)

In this example, the program captures and prints the coordinates of the mouse as it moves or is
dragged across the window.
PART C (1 × 15 = 15 marks)

16. (a) Create a Central Library Management System with Libraries in Different Locations in a
City. Each Library Can Order a Book from the Central Library and Give It to the Requesting
Customers. Availability of That Book Should Be Updated on Each Lending. Consider Each
Library as a Thread That Requests for a Book for Purchase from the Central Library. If the
Requested Book Count is Less Than Zero, Then Central Library Provides an Appropriate
Message to the Appropriate Requesting Library. Implement Using Multithreading. (15 marks)

Introduction to Multithreading in Java

Multithreading is the ability of a CPU to provide multiple threads of execution concurrently.


Java provides built-in support for multithreading through the Thread class and Runnable
interface. In this scenario, each library acts as a separate thread, requesting books from the
central library.

Problem Overview

In this problem:

 A CentralLibrary keeps track of available books.


 Multiple BranchLibraries request books from the Central Library.
 When a book is lent out, the count should decrease.
 If a requested book is not available, an appropriate message should be shown.

Java Code Implementation


java
Copy code
class CentralLibrary {
private int availableBooks;

public CentralLibrary(int books) {


this.availableBooks = books;
}

// Method to lend a book


public synchronized boolean lendBook() {
if (availableBooks > 0) {
availableBooks--;
return true;
} else {
return false;
}
}

public int getAvailableBooks() {


return availableBooks;
}
}

class BranchLibrary extends Thread {


private CentralLibrary centralLibrary;

public BranchLibrary(CentralLibrary library) {


this.centralLibrary = library;
}

public void run() {


if (centralLibrary.lendBook()) {
System.out.println(Thread.currentThread().getName() + " borrowed a
book. Books remaining: " + centralLibrary.getAvailableBooks());
} else {
System.out.println(Thread.currentThread().getName() + " failed to
borrow a book. No books available.");
}
}
}

public class LibrarySystem {


public static void main(String[] args) {
CentralLibrary centralLibrary = new CentralLibrary(5); // Central
library has 5 books

// Creating threads (Branch Libraries)


BranchLibrary branch1 = new BranchLibrary(centralLibrary);
BranchLibrary branch2 = new BranchLibrary(centralLibrary);
BranchLibrary branch3 = new BranchLibrary(centralLibrary);
BranchLibrary branch4 = new BranchLibrary(centralLibrary);
BranchLibrary branch5 = new BranchLibrary(centralLibrary);
BranchLibrary branch6 = new BranchLibrary(centralLibrary);

// Starting the threads


branch1.start();
branch2.start();
branch3.start();
branch4.start();
branch5.start();
branch6.start();
}
}

Explanation of Code:
1. CentralLibrary Class: The class manages the available books. The lendBook() method is
synchronized to ensure that only one library can access the book at a time.
2. BranchLibrary Class: Each branch library is a thread that requests a book from the central
library. It tries to borrow a book and prints the status.
3. LibrarySystem Class: The main class creates a central library with 5 books and starts multiple
branch libraries as threads.

Output:
less
Copy code
Thread-0 borrowed a book. Books remaining: 4
Thread-1 borrowed a book. Books remaining: 3
Thread-2 borrowed a book. Books remaining: 2
Thread-3 borrowed a book. Books remaining: 1
Thread-4 borrowed a book. Books remaining: 0
Thread-5 failed to borrow a book. No books available.

In this output:

 The first five branches successfully borrow a book.


 The sixth branch fails since no books are available.

Conclusion

This example demonstrates how multithreading is used to simulate real-time interactions


between multiple branch libraries and a central library, allowing for concurrency in handling
book requests.

16. (b)

With Neat Example, Explain Java AWT Menu Bars and Menu Items. (15 marks)

Introduction to AWT Menu Bars and Menu Items

Java AWT (Abstract Window Toolkit) provides a set of GUI components, and one of them is the
Menu components. A menu bar contains multiple menus, each containing individual menu
items. These are used to provide a user interface for operations like File, Edit, Help, etc.

 MenuBar: A container for the menus.


 Menu: Represents a list of items (like File, Edit) that can be clicked.
 MenuItem: Represents an individual item in a menu (like Open, Save, etc.).
 CheckBoxMenuItem and RadioMenuItem: Specialized types of menu items for checkboxes and
radio buttons.

Steps to Create Menu Bar with Menu Items in AWT:

1. Create a Frame: A window to place the menu.


2. Create Menu Bar: An object of MenuBar.
3. Create Menus: Add menus to the menu bar (e.g., File, Edit).
4. Create Menu Items: Add items to each menu (e.g., New, Open, Save).
5. Set Menu Bar to Frame: Finally, assign the MenuBar to the frame.

Code Example for AWT Menu Bar and Menu Items

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

public class MenuBarExample extends Frame {

public MenuBarExample() {
// Create a menu bar
MenuBar menuBar = new MenuBar();

// Create "File" menu


Menu fileMenu = new Menu("File");

// Create menu items for "File"


MenuItem newItem = new MenuItem("New");
MenuItem openItem = new MenuItem("Open");
MenuItem saveItem = new MenuItem("Save");
MenuItem exitItem = new MenuItem("Exit");

// Add action listener to menu items


exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});

// Add menu items to "File" menu


fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.addSeparator(); // Adding a separator
fileMenu.add(exitItem);

// Create "Edit" menu


Menu editMenu = new Menu("Edit");

// Create menu items for "Edit"


MenuItem cutItem = new MenuItem("Cut");
MenuItem copyItem = new MenuItem("Copy");
MenuItem pasteItem = new MenuItem("Paste");

// Add menu items to "Edit" menu


editMenu.add(cutItem);
editMenu.add(copyItem);
editMenu.add(pasteItem);

// Add menus to the menu bar


menuBar.add(fileMenu);
menuBar.add(editMenu);

// Set the menu bar for the frame


setMenuBar(menuBar);

// Set up frame
setTitle("AWT MenuBar Example");
setSize(400, 300);
setVisible(true);
}

public static void main(String[] args) {


new MenuBarExample();
}
}

Explanation of the Code:

1. MenuBar Creation: We create a MenuBar object, which will contain our menus (File, Edit).
2. Menu Creation: For each category (e.g., "File", "Edit"), we create a Menu object.
3. MenuItem Creation: We create several MenuItem objects, which represent the individual
clickable items in a menu (e.g., "New", "Open", "Save").
4. Adding Items to Menu: Menu items are added to the corresponding menus, and each menu is
added to the menu bar.
5. Setting Menu Bar: The menu bar is set to the frame using setMenuBar(menuBar).
6. Exit Action: We added an ActionListener to the "Exit" menu item to close the application.

Output:

This program will display a window with a menu bar at the top, which contains the "File" and
"Edit" menus. Each menu will have items like New, Open, Save, Cut, Copy, Paste, and Exit.
When you click "Exit", the application will close.
Conclusion

The AWT MenuBar component is an essential part of the GUI that allows developers to create
interactive menus. It can be used to add functionalities like opening files, saving files, or
performing actions like cutting, copying, and pasting.

Summary of Topics Covered So Far:

1. Object-Oriented Programming vs. Procedure-Oriented Programming


o OOP focuses on objects and classes, while POP focuses on functions or procedures.
o OOP promotes code reusability and modularity through inheritance, polymorphism, etc.
o POP emphasizes a linear sequence of instructions.

2. Java Program for Finding the Greatest of Three Numbers


o Involves taking three numbers as input and comparing them using conditional
statements.

3. Constructor in Java
o Constructors are special methods used to initialize objects. They can be default or
parameterized.

4. Java Program for Student Grade Calculation Using Methods


o A program that uses methods to input marks, compute the average, and display the
grade.

5. Java Interface for Library System


o A program demonstrating the use of interfaces with drawBook(), returnBook(), and
checkStatus() methods.

6. Method Overloading
o Java allows methods with the same name but different parameters (number or type).

7. Packages in Java
o Packages are used to group related classes, which helps organize code and avoid name
conflicts.

8. Java Exception Handling


o The try-catch-finally block is used for handling exceptions in a clean and
organized manner.

9. Java String Handling


o String operations like comparison, reversal, and case conversion.

10. AWT Menus and MenuItems


 AWT components such as MenuBar, Menu, and MenuItem are used to create interactive menus
in Java applications.

You might also like