Java Practical Slips Solution
Java Practical Slips Solution
Java Practical Slips Solution
Q1) Write a Program to print all Prime numbers in an array of 'n' elements. (use command line
arguments)
import java.util.Scanner;
// Parameterized constructor
public Staff(int id, String name) {
this.id = id;
this.name = name;
}
// Subclass OfficeStaff
class OfficeStaff extends Staff {
private String department;
// Parameterized constructor
public OfficeStaff(int id, String name, String department) {
super(id, name); // Call the constructor of the abstract class
this.department = department;
}
// Main class
public class StaffTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.close();
}
}
Slip no-2
Q1) Write a program to read the First Name and Last Name of a person, his weight and height
using command line arguments. Calculate the BMI Index which is defined as the individual's
body mass divided by the square of their height.
// Calculate BMI
double bmi = weight / (height * height);
// Display result
System.out.println("Person: " + firstName + " " + lastName);
System.out.println("Weight: " + weight + " kg");
System.out.println("Height: " + height + " meters");
System.out.println("BMI Index: " + String.format("%.2f", bmi));
import java.util.Arrays;
import java.util.Scanner;
class CricketPlayer {
String name;
int noOfInnings;
int noOfTimesNotOut;
int totalRuns;
double batAvg;
scanner.close();
}
}
Slip no-3
Q1. Write a program to accept 'n' name of cities from the user and sort them in ascending order.
import java.util.Scanner;
import java.util.Arrays;
scanner.close();
}
}
class Patient {
String patientName;
int patientAge;
double patientOxyLevel;
double patientHRCTReport;
public Patient(String patientName, int patientAge, double
patientOxyLevel, double patientHRCTReport) {
this.patientName = patientName;
this.patientAge = patientAge;
this.patientOxyLevel = patientOxyLevel;
this.patientHRCTReport = patientHRCTReport;
}
try {
patient.checkPatientStatus();
} catch (CovidPositiveException e) {
System.out.println(e.getMessage());
}
}
}
Slip no-4
Q1) Write a program to print an array after changing the rows and columns of a given
two-dimensional array.
import java.util.Scanner;
// Create a 2D array
int[][] matrix = new int[rows][cols];
scanner.close();
}
}
Q2) Write a program to design a screen using Awt that will take a user name and password. It
the user name and Jpassword are not same, raise an Exception with appropriate message User
can have 3 login chances only. Use clear button to clear the TextFields.
import java.awt.*;
import java.awt.event.*;
public LoginScreenAWT() {
setTitle("Login Screen");
setSize(400, 200);
setLayout(new GridLayout(4, 2));
add(userLabel);
add(userField);
add(passLabel);
add(passField);
add(loginButton);
add(clearButton);
add(messageLabel);
loginButton.addActionListener(this);
clearButton.addActionListener(this);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose();
}
});
}
if (attempts < 3) {
if (username.equals(password)) {
messageLabel.setText("Login Successful!");
} else {
attempts++;
messageLabel.setText("Incorrect Login. Attempts left:
" + (3 - attempts));
if (attempts >= 3) {
messageLabel.setText("Login Failed. No more
attempts.");
loginButton.setEnabled(false);
}
}
}
}
}
Slip no-5
Q1) Write a program for multilevel inheritance such that Country is inherited from Continent
State is inherited from Country. Display the place, State, Country and Continent
// Main class
public class MultilevelInheritance {
public static void main(String[] args) {
// Create an object of State
State state = new State("Asia", "India", "Maharashtra", "Mumbai");
// Display details
state.displayDetails();
}
}
Q2) Write a menu driven program to perform the following operations on multidimensional array
ic matrices:
Addition
Multiplication
Exit
import java.util.Scanner;
do {
System.out.println("\nMenu:");
System.out.println("1. Addition of two matrices");
System.out.println("2. Multiplication of two matrices");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1: {
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int cols = scanner.nextInt();
if (colsA != rowsB) {
System.out.println("Matrices cannot be multiplied:
incompatible dimensions.");
break;
}
scanner.close();
}
}
Slip no-6
Q2) Create an abstract class "order" having members id, description. Create two subclasses
"Purchase Order" and "Sales Order" having members customer name and Vendor name
respectively. Definemethods accept and display in all cases. Create 3 objects each of Purchas
Order and Sales Order and accept and display details.
import java.util.Scanner;
// Subclass PurchaseOrder
class PurchaseOrder extends Order {
private String customerName;
@Override
public void acceptDetails() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Customer Name for Purchase Order (ID: " +
id + "): ");
customerName = scanner.nextLine();
}
@Override
public void displayDetails() {
System.out.println("Purchase Order ID: " + id);
System.out.println("Description: " + description);
System.out.println("Customer Name: " + customerName);
System.out.println();
}
}
// Subclass SalesOrder
class SalesOrder extends Order {
private String vendorName;
@Override
public void acceptDetails() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Vendor Name for Sales Order (ID: " + id +
"): ");
vendorName = scanner.nextLine();
}
@Override
public void displayDetails() {
System.out.println("Sales Order ID: " + id);
System.out.println("Description: " + description);
System.out.println("Vendor Name: " + vendorName);
System.out.println();
}
}
// Main class
public class OrderTest {
public static void main(String[] args) {
// Create arrays for PurchaseOrder and SalesOrder
PurchaseOrder[] purchaseOrders = new PurchaseOrder[3];
SalesOrder[] salesOrders = new SalesOrder[3];
Slip no-7
Q1) Design a class for Bank. Bank Class should support following operations;
import java.util.Scanner;
// BankAccount class
class BankAccount {
private String accountHolder;
private double balance;
// Bank class
public class Bank {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\nBank Operations Menu:");
System.out.println("1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. Check Balance");
System.out.println("4. Exit");
System.out.print("Select an option: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter amount to deposit: $");
double depositAmount = scanner.nextDouble();
account.deposit(depositAmount);
break;
case 2:
System.out.print("Enter amount to withdraw: $");
double withdrawAmount = scanner.nextDouble();
account.withdraw(withdrawAmount);
break;
case 3:
System.out.println("Current Balance for " +
account.getAccountHolder() + ": $" + account.getBalance());
break;
case 4:
System.out.println("Exiting...");
scanner.close();
return;
default:
System.out.println("Invalid option. Please try
again.");
}
}
}
}
Q2) Write a program to accept a text file from user and display the contents of a file in reverse
order and change its case.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class ReverseCaseFileContent {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the path of the text file: ");
String filePath = scanner.nextLine();
scanner.close();
}
Slip no-8
Q1) Create a class Sphere, to calculate the volume and surface area of sphere.
scanner.close();
}
}
Q2) Design a screen to handle the Mouse Events such as MOUSE_MOVED and
MOUSE_CLICKED and display the position of the Mouse_Click in a TextField
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public MouseEventExample() {
// Set up the frame
setTitle("Mouse Events Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null); // Using null layout for manual positioning
addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
// Optionally display mouse position while moving
int x = e.getX();
int y = e.getY();
textField.setText("Mouse Moved at: (" + x + ", " + y +
")");
}
});
}
Slip no-9
// Constructor
public Clock(int hours, int minutes, int seconds) {
if (isValidTime(hours, minutes, seconds)) {
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
this.period = (hours < 12) ? "AM" : "PM"; // Set AM/PM based
on hours
} else {
throw new IllegalArgumentException("Invalid time provided.");
}
}
// Marker interface
interface ProductMarker {
// This is a marker interface with no methods
}
// Default constructor
public Product() {
this.productId = 0;
this.productName = "Unknown";
this.productCost = 0.0;
this.productQuantity = 0;
objectCount++; // Increment object count
}
// Parameterized constructor
public Product(int productId, String productName, double productCost,
int productQuantity) {
this.productId = productId;
this.productName = productName;
this.productCost = productCost;
this.productQuantity = productQuantity;
objectCount++; // Increment object count
}
Slip no-10
Q1) Write a program to find the cube of given number using functional interface.
// Functional interface
@FunctionalInterface
interface CubeCalculator {
int calculateCube(int number);
}
package student;
import java.util.Scanner;
double totalMarks = 0;
int subjects = 6;
// Calculate percentage
double percentage = (totalMarks / (subjects * 100)) * 100;
Slip no-11
Q1) Define an interface "Operation" which has method volume().Define a constant PI having a
value 3.142 Create a class cylinder which implements this interface (members - radius, height).
Create one object and calculate the volume.
// Interface Operation
interface Operation {
double PI = 3.142; // Constant for PI
double volume(); // Method to calculate volume
}
Q2) Write a program to accept the username and password from user if username and
password are not same then raise "Invalid Password" with appropriate msg.
import java.util.Scanner;
Slip no-12
Q1) Write a program to create parent class College(cno, cname, caddr) and derived class
Department(dno, dname) from College. Write a necessary methods to display College details.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Frame
JFrame frame;
public SimpleCalculator() {
// Create the frame
frame = new JFrame("Simple Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(420, 550);
frame.setLayout(null);
textField.setText(textField.getText().concat(String.valueOf(i)));
}
}
if (e.getSource() == decButton) {
textField.setText(textField.getText().concat("."));
}
if (e.getSource() == addButton) {
num1 = Double.parseDouble(textField.getText());
operator = '+';
textField.setText("");
}
if (e.getSource() == subButton) {
num1 = Double.parseDouble(textField.getText());
operator = '-';
textField.setText("");
}
if (e.getSource() == mulButton) {
num1 = Double.parseDouble(textField.getText());
operator = '*';
textField.setText("");
}
if (e.getSource() == divButton) {
num1 = Double.parseDouble(textField.getText());
operator = '/';
textField.setText("");
}
if (e.getSource() == equButton) {
num2 = Double.parseDouble(textField.getText());
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
textField.setText(String.valueOf(result));
num1 = result;
}
if (e.getSource() == clrButton) {
textField.setText("");
}
if (e.getSource() == delButton) {
String string = textField.getText();
textField.setText("");
for (int i = 0; i < string.length() - 1; i++) {
textField.setText(textField.getText() + string.charAt(i));
}
}
}
Slip no-13
Q1) Write a program to accept a file name from command prompt, if the file exits then display
number of words and lines in that file.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
Q2) Write a program to display the system date and time in various formats shown below:
Current date and time is: Fri August 31 15:25:59 IST 2021
Current date and time is: 31/08/21 15:25:59 PM +0530
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Date;
Slip no-14
Q1) Write a program to accept a number from the user, if number is zero then throw user
defined exception "Number is 0" otherwise check whether no is prime or not (Use static
keyword).
import java.util.Scanner;
try {
// Check if the number is zero and throw exception
if (number == 0) {
throw new ZeroException("Number is 0");
}
Q2) Write a Java program to create a Package "SY" which has a class SYMarks (members -
ComputerTotal, MathsTotal, and ElectronicsTotal). Create another package TY which has a
class TYMarks (members - Theory, Practicals). Create 'n' objects of Student class (having
rollNumber, name, SYMarks and TYMarks). Add the marks of SY and TY computer subjects
and calculate the Grade ('A' for >= 70, 'B' for >= 60 'C' for >= 50, Pass Class for >=40 else
FAIL') and display the result of the student in proper format.
import SY.SYMarks;
import TY.TYMarks;
import java.util.Scanner;
class Student {
private String rollNumber;
private String name;
private SYMarks syMarks;
private TYMarks tyMarks;
displayResult(grade);
}
System.out.print("Name: ");
String name = scanner.nextLine();
student.calculateGrade();
}
scanner.close();
}
}
Slip no-15
Q1) Accept the names of two files and copy the contents of the first to the second. First file
having Book name and Author name in file.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
copyFileContents(sourceFileName, destinationFileName);
scanner.close();
}
String line;
// Read from the source file and write to the destination file
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine(); // Write a new line after each line
}
} catch (IOException e) {
System.out.println("An error occurred while copying the file:
" + e.getMessage());
}
}
}
Q2) Write a program to define a class Account having members custname, accno. Define
default and parameterized constructor. Create a subclass called SavingAccount with member
savingbal, minbal. Create a derived class AccountDetail that extends the class SavingAccount
with members, depositamt and withdrawalamt. Write a appropriate method to display customer
details.
// Default constructor
public Account() {
this.custName = "Unknown";
this.accNo = "0000";
}
// Parameterized constructor
public Account(String custName, String accNo) {
this.custName = custName;
this.accNo = accNo;
}
}
// Subclass: SavingAccount
class SavingAccount extends Account {
protected double savingBal;
protected double minBal;
// Default constructor
public SavingAccount() {
super(); // Call to Account default constructor
this.savingBal = 0.0;
this.minBal = 500.0; // Default minimum balance
}
// Parameterized constructor
public SavingAccount(String custName, String accNo, double savingBal,
double minBal) {
super(custName, accNo); // Call to Account parameterized
constructor
this.savingBal = savingBal;
this.minBal = minBal;
}
}
// Default constructor
public AccountDetail() {
super(); // Call to SavingAccount default constructor
this.depositAmt = 0.0;
this.withdrawalAmt = 0.0;
}
// Parameterized constructor
public AccountDetail(String custName, String accNo, double savingBal,
double minBal, double depositAmt, double withdrawalAmt) {
super(custName, accNo, savingBal, minBal); // Call to
SavingAccount parameterized constructor
this.depositAmt = depositAmt;
this.withdrawalAmt = withdrawalAmt;
}
Slip no-16
Q1) Write a program to find the Square of given number using function interface
import java.util.Scanner;
// Functional interface
@FunctionalInterface
interface Square {
double calculateSquare(double number);
}
import java.awt.*;
import java.awt.event.*;
Slip no-17
Q1) Design a Super class Customer (name, phone-number). Derive a class Depositor(accno,
balance) from Customer. Again, derive a class Borrower (loan-no, loan-amt) from Depositor.
Write necessary member functions to read and display the details of 'n'customers.
import java.util.Scanner;
// Superclass: Customer
class Customer {
protected String name;
protected String phoneNumber;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Create buttons
JButton concatButton = new JButton("Concatenate");
JButton reverseButton = new JButton("Reverse");
Slip no18
import javax.swing.*;
import java.awt.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
class CricketPlayer {
String name;
int noOfInnings;
int noOfTimesNotOut;
int totalRuns;
double batAvg;
// Constructor
public CricketPlayer(String name, int noOfInnings, int
noOfTimesNotOut, int totalRuns) {
this.name = name;
this.noOfInnings = noOfInnings;
this.noOfTimesNotOut = noOfTimesNotOut;
this.totalRuns = totalRuns;
this.batAvg = avg(noOfInnings, noOfTimesNotOut, totalRuns);
}
scanner.close();
}
}
Slip no-19
Q1) Write a program to accept the two dimensional array from user and display sum of its
diagonal elements.
import java.util.Scanner;
public class DiagonalSum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.close();
}
}
Q2) Write a program which shows the combo box which includes list of T.Y.B.Sc.(Comp. Sci)
subjects. Display the selected subject in a text field.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
Slip no-20
Q1) Write a Program to illustrate multilevel Inheritance such that country is inherited from
continent. State is inherited from country. Display the place, state, country and continent.
// Base class
class Continent {
protected String continentName;
Q2) Write a package for Operation, which has two classes, Addition and Maximum. Addition has
two methods add () and subtract (), which are used to add two integers and subtract two, float
values respectively. Maximum has a method max () to display the maximum of two integers
import java.util.Scanner;
// Demonstrate addition
int sum = addition.add(num1, num2);
System.out.println("Sum of " + num1 + " and " + num2 + ": " +
sum);
// Demonstrate subtraction
float difference = addition.subtract(float1, float2);
System.out.println("Difference between " + float1 + " and " +
float2 + ": " + difference);
// Demonstrate maximum
int max = maximum.max(maxNum1, maxNum2);
System.out.println("Maximum of " + maxNum1 + " and " + maxNum2 +
": " + max);
// Close scanner
scanner.close();
}
}
Slip no-21
Q1) Define a class MyDate(Day, Month, year) with methods to accept and display a
MyDateobject. Accept date as dd,mm,yyyy. Throw user defined exception
"InvalidDateException" if the date is invalid.
import java.util.Scanner;
// Constructor
public MyDate(int day, int month, int year) throws
InvalidDateException {
if (!isValidDate(day, month, year)) {
throw new InvalidDateException("Invalid Date: " + day + "/" +
month + "/" + year);
}
this.day = day;
this.month = month;
this.year = year;
}
Q2) Create an employee class(id, name, deptname, salary). Define a default and parameterized
constructor. Use 'this' keyword to initialize instance variables. Keep a count of objects created.
Create objects using parameterized constructor and display the object count after each object is
created. (Use static member and method). Also display the contents of each object.
class Employee {
private int id;
private String name;
private String deptname;
private double salary;
private static int objectCount = 0; // Static variable to keep track
of object count
// Default constructor
public Employee() {
this(0, "Unknown", "Unknown", 0.0); // Default values, using the
parameterized constructor
}
// Parameterized constructor
public Employee(int id, String name, String deptname, double salary) {
this.id = id;
this.name = name;
this.deptname = deptname;
this.salary = salary;
objectCount++; // Increment object count when an object is
created
}
Slip no-22
Q1) Write a program to create an abstract class named Shape that contains two integers and an
empty method named printArea(). Provide three classes named Rectangle, Triangle and Circle
such that each one of the classes extends the class Shape. Each one of the classes contain
only the method printArea() that prints the area of the given shape. (use method overriding).
Q2) Write a program that handles all mouse events and shows the event name at the center of
the Window, red in color when a mouse event is fired. (Use adapter classes).
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public MouseEventDemo() {
// Set up the frame
setTitle("Mouse Event Demo");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
@Override
public void mouseEntered(MouseEvent e) {
label.setText("Mouse Entered");
}
@Override
public void mouseExited(MouseEvent e) {
label.setText("Mouse Exited");
}
@Override
public void mousePressed(MouseEvent e) {
label.setText("Mouse Pressed");
}
@Override
public void mouseReleased(MouseEvent e) {
label.setText("Mouse Released");
}
});
addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
label.setText("Mouse Moved");
}
@Override
public void mouseDragged(MouseEvent e) {
label.setText("Mouse Dragged");
}
});
// Set the frame visible
setVisible(true);
}
Slip no-23
Q1) Define a class MyNumber having one private int data member. Write a default constructor
to initialize it to 0 and another constructor to initialize it to a value (Use this). Write methods
isNegative, is Positive, isZero, isOdd, isEven. Create an object in main. Use command line
arguments to pass a value to the Object.
class MyNumber {
// Private data member
private int number;
if (isOdd()) {
System.out.println("The number is Odd.");
} else {
System.out.println("The number is Even.");
}
}
try {
// Parse the command-line argument to an integer
int inputNumber = Integer.parseInt(args[0]);
Q2) Write a simple currency converter, as shown in the figure. User can enter the amount of
"Singapore Dollars", "US Dollars", or "Euros", in floating-point number. The converted values
shall be displayed to 2 decimal places. Assume that 1 USD = 1.41 SGD, 1 USD = 0.92 Euro, 1
SGID=0.65 Euro.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
// Labels
JLabel sgdLabel = new JLabel("Singapore Dollars");
sgdLabel.setBounds(20, 20, 120, 30);
frame.add(sgdLabel);
// Button to calculate
JButton convertButton = new JButton("Convert");
convertButton.setBounds(270, 20, 100, 30);
frame.add(convertButton);
// Conversion rates
double usdToSgd = 1.41;
double usdToEuro = 0.92;
double sgdToEuro = 0.65;
if (!sgdText.isEmpty()) {
double sgd = Double.parseDouble(sgdText);
usdField.setText(df.format(sgd / usdToSgd));
euroField.setText(df.format(sgd * sgdToEuro));
} else if (!usdText.isEmpty()) {
double usd = Double.parseDouble(usdText);
sgdField.setText(df.format(usd * usdToSgd));
euroField.setText(df.format(usd * usdToEuro));
} else if (!euroText.isEmpty()) {
double euro = Double.parseDouble(euroText);
usdField.setText(df.format(euro / usdToEuro));
sgdField.setText(df.format(euro / sgdToEuro));
}
}
});
frame.setVisible(true);
}
}
Slip no-24
Q1) Create an abstract class 'Bank' with an abstract method 'getBalance'. Rs. 100, Rs.150 and
Rs.200 are deposited in banks A, B and C respectively. 'BankA', 'BankB' and 'BankC are
subclasses of class 'Bank', each having a method named 'getBalance'. Call this method by
creating an object of each of the three classes.
Q2) Program that displays three concentric circles where ever the user clicks the mouse on a
frame. The program must exit when user clicks 'X' on the frame.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public ConcentricCircles() {
setTitle("Concentric Circles");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
@Override
public void paint(Graphics g) {
super.paint(g);
// Draw three concentric circles centered at the clicked position
g.drawOval(x - 30, y - 30, 60, 60);
g.drawOval(x - 60, y - 60, 120, 120);
g.drawOval(x - 90, y - 90, 180, 180);
}
Slip no-25
Q1) Create a class Student(rollno, name,class, per), to read student information from the
console and display them (Using BufferedReader class)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Student {
// Data members of the Student class
private int rollno;
private String name;
private String studentClass;
private double percentage;
Q2) Create the following GUI screen using appropriate layout manager. Accept the name, class,
hobbies from the user and display the selected options in a textbox
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Create a panel
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(6, 2));
// Your Name
JLabel nameLabel = new JLabel("Your Name");
JTextField nameField = new JTextField();
panel.add(nameLabel);
panel.add(nameField);
// Your Class
JLabel classLabel = new JLabel("Your Class");
ButtonGroup classGroup = new ButtonGroup();
JRadioButton fyRadio = new JRadioButton("FY");
JRadioButton syRadio = new JRadioButton("SY");
JRadioButton tyRadio = new JRadioButton("TY");
classGroup.add(fyRadio);
classGroup.add(syRadio);
classGroup.add(tyRadio);
panel.add(classLabel);
// Your Hobbies
JLabel hobbiesLabel = new JLabel("Your Hobbies");
JCheckBox musicCheckBox = new JCheckBox("Music");
JCheckBox danceCheckBox = new JCheckBox("Dance");
JCheckBox sportsCheckBox = new JCheckBox("Sports");
panel.add(hobbiesLabel);
// Output TextField
JTextField outputField = new JTextField();
outputField.setEditable(false);
// Submit Button
JButton submitButton = new JButton("Submit");
submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String selectedClass = fyRadio.isSelected() ? "FY" :
syRadio.isSelected() ? "SY" : tyRadio.isSelected() ? "TY" : "";
String hobbies = "";
if (musicCheckBox.isSelected()) hobbies += "Music ";
if (danceCheckBox.isSelected()) hobbies += "Dance ";
if (sportsCheckBox.isSelected()) hobbies += "Sports ";
panel.add(submitButton);
panel.add(outputField);
Slip no-26
Q1) Define a Item class (item_number, item_name, item_price). Define a default and
parameterized constructor. Keep a count of objects created. Create objects using parameterized
constructor and display the object count after each object is created. (Use static member and
method). Also display the contents of each object.
class Item {
// Instance variables
private int item_number;
private String item_name;
private double item_price;
// Default constructor
public Item() {
this.item_number = 0;
this.item_name = "Unknown";
this.item_price = 0.0;
itemCount++; // Increment item count when an object is created
}
// Parameterized constructor
public Item(int item_number, String item_name, double item_price) {
this.item_number = item_number;
this.item_name = item_name;
this.item_price = item_price;
itemCount++; // Increment item count when an object is created
}
import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
// Parameterized constructor
public Donor(String name, int age, String address, String
contactNumber, String bloodGroup, String lastDonationDate) {
this.name = name;
this.age = age;
this.address = address;
this.contactNumber = contactNumber;
this.bloodGroup = bloodGroup;
this.lastDonationDate = lastDonationDate;
}
// Read donor objects from the file and filter based on blood
group and donation date
System.out.println("\nDonors with A+ve blood group who haven't
donated in the last 6 months:");
try (ObjectInputStream ois = new ObjectInputStream(new
FileInputStream(fileName))) {
while (true) {
try {
Donor donor = (Donor) ois.readObject();
if (donor.isEligibleDonor()) {
donor.displayDonorDetails();
}
} catch (EOFException eof) {
break; // End of file reached
}
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Slip no-27
Q1) Define an Employee class with suitable attributes having getSalary() method, which returns
salary withdrawn by a particular employee. Write a class Manager which extends a class
Employee, override the getSalary() method, which will return salary of manager by adding
traveling allowance, house rent allowance etc.
// Constructor
public Employee(String name, double basicSalary) {
this.name = name;
this.basicSalary = basicSalary;
}
// Constructor
public Manager(String name, double basicSalary, double
travelAllowance, double houseRentAllowance) {
super(name, basicSalary); // Call to the superclass constructor
this.travelAllowance = travelAllowance;
this.houseRentAllowance = houseRentAllowance;
}
// Overriding getSalary() method
@Override
public double getSalary() {
// Calculate manager's salary including allowances
return super.getSalary() + travelAllowance + houseRentAllowance;
}
Q2) Write a program to accept a string as command line argument and check whether it is a file
or directory. Also perform operations as follows:
i) If it is a directory, delete all text files in that directory. Confirm delete operation from user
before deleting text files. Also, display a count showing the number of files deleted, if any, from
the directory.
Slip no-29
Q1) Write a program to create a class Customer(custno,custname,contactnumber,custaddr).
Write a method to search the customer name with given contact number and display the details.
import java.util.ArrayList;
import java.util.Scanner;
class Customer {
private int custNo;
private String custName;
private String contactNumber;
private String custAddr;
// Constructor
public Customer(int custNo, String custName, String contactNumber,
String custAddr) {
this.custNo = custNo;
this.custName = custName;
this.contactNumber = contactNumber;
this.custAddr = custAddr;
}
if (!found) {
System.out.println("Customer not found with contact number: "
+ contactNumber);
}
scanner.close();
}
}