Question Paper 4 Java
Question Paper 4 Java
Example: A .class file compiled on Windows can run on Linux or Mac if the JVM is
installed.
class Demo {
Demo() { // Constructor
System.out.println("Constructor called!");
}
void display() { // Method
System.out.println("Method called!");
}
}
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);
}
}
Example:
Example:
Example:
Part B – (5 × 13 = 65 marks)
11.
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.
Procedure-Oriented Programming
Feature Object-Oriented Programming (OOP)
(POP)
Data and functions are encapsulated into Data is separate from functions and
Data Encapsulation
classes and objects. passed between them.
Example Paradigms Java, Python, C++, C#, etc. C, Fortran, Assembly, etc.
Solution: The program will take three numbers as input, compare them, and display the greatest
one.
import java.util.Scanner;
Output:
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.
class Student {
String name;
int age;
// Parameterized Constructor
Student(String n, int a) {
name = n;
age = a;
}
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;
Output:
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();
}
@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);
}
}
Output:
Books available: 5
Book drawn. Remaining books: 4
Books available: 4
Book returned. Available books: 5
Books available: 5
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.
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
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.
class Item {
int itemNo;
String itemDescription;
int quantity;
double costPrice;
class Store {
Item[] items;
// Update stock
store.updateStock(102, 5);
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:
Discuss About Try, Catch, and Finally Keywords in Exception Handling with an Example. (8
marks)
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).
Explanation:
Output:
13. (b) (ii) List and Explain Data Types and Their Corresponding Wrapper Classes. (5 marks)
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
Example:
// 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:
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.
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.
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
Output:
14. (a) (ii) Outline Parameter Type Bounds with an Example. (7 marks)
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.
The upper bound restricts the type to be the specified class or its subclass.
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).
The lower bound restricts the type to be the specified class or its superclasses.
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.
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.
// 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)
1. JButton: Standard button used for actions such as submitting a form or triggering an
event.
3. JRadioButton: A button that allows users to choose only one option from a set of
options.
4. JToggleButton: A button that can be toggled on or off. Similar to a checkbox but looks
like a button.
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.
import java.awt.*;
import java.awt.event.*;
public MouseListenerExample() {
// Set up the frame
setTitle("MouseListener Example");
setSize(400, 300);
addMouseListener(this); // Adding MouseListener to the frame
setVisible(true);
}
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.
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:
public MouseMotionListenerExample() {
// Set up the frame
setTitle("MouseMotionListener Example");
setSize(400, 300);
addMouseMotionListener(this); // Adding MouseMotionListener to the
frame
setVisible(true);
}
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)
Problem Overview
In this problem:
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:
Conclusion
16. (b)
With Neat Example, Explain Java AWT Menu Bars and Menu Items. (15 marks)
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.
import java.awt.*;
import java.awt.event.*;
public MenuBarExample() {
// Create a menu bar
MenuBar menuBar = new MenuBar();
// Set up frame
setTitle("AWT MenuBar Example");
setSize(400, 300);
setVisible(true);
}
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.
3. Constructor in Java
o Constructors are special methods used to initialize objects. They can be default or
parameterized.
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.