0% found this document useful (0 votes)
17 views146 pages

Java Slips

The document contains multiple programming tasks in Java, including printing prime numbers, calculating BMI, sorting city names, handling patient health checks, and implementing multilevel inheritance. Each task is accompanied by code snippets demonstrating the required functionality, such as using command line arguments, handling exceptions, and utilizing AWT for GUI applications. The document also includes sample outputs for various programs to illustrate their expected behavior.

Uploaded by

nanditavetal646
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views146 pages

Java Slips

The document contains multiple programming tasks in Java, including printing prime numbers, calculating BMI, sorting city names, handling patient health checks, and implementing multilevel inheritance. Each task is accompanied by code snippets demonstrating the required functionality, such as using command line arguments, handling exceptions, and utilizing AWT for GUI applications. The document also includes sample outputs for various programs to illustrate their expected behavior.

Uploaded by

nanditavetal646
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 146

Slip 1

Q1) Write a Program to print all Prime numbers in an array of ‘n’ elements.(use command line
arguments).

public class PrimeArray {

// Function to check if a number is prime

public static boolean isPrime(int num) {

if (num <= 1) return false;

for (int i = 2; i <= Math.sqrt(num); i++) {

if (num % i == 0) return false;

return true;

public static void main(String[] args) {

if (args.length == 0) {

System.out.println("Please enter numbers as command line arguments.");

return;

System.out.println("Prime numbers in the array:");

for (int i = 0; i < args.length; i++) {

int num = Integer.parseInt(args[i]);

if (isPrime(num)) {

System.out.print(num + " ");

}
Q2) Define an abstract class Staff with protected members id and name. Define a
parameterizedconstructor. Define one subclass OfficeStaff with member department. Create n
objects ofOfficeStaff and display all details.

// Abstract class Staff

abstract class Staff {

protected int id;

protected String name;

// Parameterized constructor

public Staff(int id, String name) {

this.id = id;

this.name = name;

// Abstract method to display details

abstract void display();

// Subclass OfficeStaff

class OfficeStaff extends Staff {

private String department;

// Constructor

public OfficeStaff(int id, String name, String department) {

super(id, name); // Call Staff constructor

this.department = department;

// Implement display method

@Override

void display() {

System.out.println("ID: " + id + ", Name: " + name + ", Department: " + department);
}

// Main class

import java.util.Scanner;

public class StaffDemo {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter number of OfficeStaff objects: ");

int n = sc.nextInt();

sc.nextLine(); // consume newline

OfficeStaff[] staffArray = new OfficeStaff[n];

for (int i = 0; i < n; i++) {

System.out.println("Enter details for staff " + (i + 1) + ":");

System.out.print("ID: ");

int id = sc.nextInt();

sc.nextLine(); // consume newline

System.out.print("Name: ");

String name = sc.nextLine();

System.out.print("Department: ");

String dept = sc.nextLine();

staffArray[i] = new OfficeStaff(id, name, dept);

System.out.println("\nDetails of all OfficeStaff:");

for (OfficeStaff staff : staffArray) {

staff.display();

}
sc.close();

output :- Enter number of OfficeStaff objects: 2

Enter details for staff 1:

ID: 101

Name: Alice

Department: HR

Enter details for staff 2:

ID: 102

Name: Bob

Department: Finance

Slip 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. (Hint : BMI = Wts. In kgs / (ht)2)

public class BMICalculator {

public static void main(String[] args) {

if (args.length != 4) {

System.out.println("Usage: java BMICalculator <FirstName> <LastName> <Weight(kg)> <Height(m)>");

return;

String firstName = args[0];

String lastName = args[1];

double weight = Double.parseDouble(args[2]);


double height = Double.parseDouble(args[3]);

// Calculate BMI

double bmi = weight / (height * height);

// Display result

System.out.println("Name: " + firstName + " " + lastName);

System.out.printf("BMI: %.2f\n", bmi);

Q2) Define a class CricketPlayer (name,no_of_innings,no_of_times_notout, totatruns, bat_avg).


Create an array of n player objects .Calculate the batting average for each player using
staticmethod avg(). Define a static sort method which sorts the array on the basis of average.
Displaythe player details in sorted orde

import java.util.Scanner;

import java.util.Arrays;

// Class CricketPlayer

class CricketPlayer {

String name;

int no_of_innings;

int no_of_times_notout;

int total_runs;

double bat_avg;

// Constructor

public CricketPlayer(String name, int innings, int notOut, int runs) {

this.name = name;

this.no_of_innings = innings;

this.no_of_times_notout = notOut;
this.total_runs = runs;

this.bat_avg = 0.0;

// Static method to calculate batting average

public static void avg(CricketPlayer player) {

if (player.no_of_innings - player.no_of_times_notout != 0)

player.bat_avg = (double) player.total_runs / (player.no_of_innings - player.no_of_times_notout);

else

player.bat_avg = player.total_runs; // if never out

// Static method to sort players by batting average

public static void sort(CricketPlayer[] players) {

Arrays.sort(players, (p1, p2) -> Double.compare(p2.bat_avg, p1.bat_avg)); // descending order

// Method to display player details

public void display() {

System.out.printf("Name: %s, Innings: %d, NotOut: %d, Total Runs: %d, Batting Avg: %.2f\n",

name, no_of_innings, no_of_times_notout, total_runs, bat_avg);

// Main class

public class CricketDemo {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter number of players: ");


int n = sc.nextInt();

sc.nextLine(); // consume newline

CricketPlayer[] players = new CricketPlayer[n];

for (int i = 0; i < n; i++) {

System.out.println("Enter details for player " + (i + 1) + ":");

System.out.print("Name: ");

String name = sc.nextLine();

System.out.print("Number of innings: ");

int innings = sc.nextInt();

System.out.print("Number of times not out: ");

int notOut = sc.nextInt();

System.out.print("Total runs: ");

int runs = sc.nextInt();

sc.nextLine(); // consume newline

players[i] = new CricketPlayer(name, innings, notOut, runs);

CricketPlayer.avg(players[i]); // calculate batting average

// Sort players by batting average

CricketPlayer.sort(players);

// Display sorted players

System.out.println("\nPlayers sorted by batting average:");

for (CricketPlayer p : players) {

p.display();

}
sc.close();

Output:- Enter number of players: 3

Enter details for player 1:

Name: Alice

Number of innings: 10

Number of times not out: 2

Total runs: 500

Enter details for player 2:

Name: Bob

Number of innings: 12

Number of times not out: 1

Total runs: 600

Enter details for player 3:

Name: Charlie

Number of innings: 8

Number of times not out: 0

Total runs: 400

Slip 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;

public class SortCities {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


System.out.print("Enter the number of cities: ");

int n = sc.nextInt();

sc.nextLine(); // Consume the newline

String[] cities = new String[n];

// Input city names

for (int i = 0; i < n; i++) {

System.out.print("Enter city " + (i + 1) + ": ");

cities[i] = sc.nextLine();

// Sort cities in ascending order

Arrays.sort(cities);

// Display sorted cities

System.out.println("\nCities in ascending order:");

for (String city : cities) {

System.out.println(city);

sc.close();

Output:- Enter the number of cities: 5

Enter city 1: Mumbai

Enter city 2: Delhi

Enter city 3: Bangalore

Enter city 4: Chennai

Enter city 5: Kolkata


Q2) Define a class patient (patient_name, patient_age,
patient_oxy_level,patient_HRCT_report).Create an object of patient. Handle appropriate
exception while patient oxygen level less than95% and HRCT scan report greater than 10, then
throw user defined Exception “Patient is CovidPositive(+) and Need to Hospitalized” otherwise
display its information

import java.util.Scanner;

// User-defined Exception

class CovidPositiveException extends Exception {

public CovidPositiveException(String message) {

super(message);

// Patient class

class Patient {

String patient_name;

int patient_age;

int patient_oxy_level;

int patient_HRCT_report;

// Constructor

public Patient(String name, int age, int oxy, int hrct) {

this.patient_name = name;

this.patient_age = age;

this.patient_oxy_level = oxy;

this.patient_HRCT_report = hrct;

// Method to check health condition

public void checkHealth() throws CovidPositiveException {

if (patient_oxy_level < 95 && patient_HRCT_report > 10) {


throw new CovidPositiveException("Patient is CovidPositive(+) and Needs to be Hospitalized");

} else {

displayInfo();

// Method to display patient info

public void displayInfo() {

System.out.println("\nPatient Information:");

System.out.println("Name: " + patient_name);

System.out.println("Age: " + patient_age);

System.out.println("Oxygen Level: " + patient_oxy_level + "%");

System.out.println("HRCT Report: " + patient_HRCT_report);

// Main class

public class PatientTest {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter Patient Name: ");

String name = sc.nextLine();

System.out.print("Enter Patient Age: ");

int age = sc.nextInt();

System.out.print("Enter Patient Oxygen Level (%): ");

int oxy = sc.nextInt();


System.out.print("Enter Patient HRCT Report Score: ");

int hrct = sc.nextInt();

Patient p = new Patient(name, age, oxy, hrct);

try {

p.checkHealth();

} catch (CovidPositiveException e) {

System.out.println("\nException: " + e.getMessage());

sc.close();

Output:- Enter Patient Name: Priya

Enter Patient Age: 30

Enter Patient Oxygen Level (%): 98

Enter Patient HRCT Report Score: 8

Slip 4

Q1) Write a program to print an array after changing the rows and columns of a given two-
dimensional array.

public class TransposeArray {

public static void main(String[] args) {

int[][] arr = {

{1, 2, 3},

{4, 5, 6}

};
int rows = arr.length;

int cols = arr[0].length;

// Create a new array for the transpose

int[][] transpose = new int[cols][rows];

// Transpose logic

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

transpose[j][i] = arr[i][j];

// Display the transposed array

System.out.println("Transposed Array:");

for (int i = 0; i < cols; i++) {

for (int j = 0; j < rows; j++) {

System.out.print(transpose[i][j] + " ");

System.out.println();

Output:- Transposed Array:

14

25

36
Q2) Write a program to design a screen using Awt that will take a user name and password. If
the user name and password 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.*;

class InvalidLoginException extends Exception {

InvalidLoginException(String msg) {

super(msg);

public class LoginAWT extends Frame implements ActionListener {

Label l1, l2, l3;

TextField t1, t2;

Button bLogin, bClear;

int attempts = 0;

LoginAWT() {

// Labels

l1 = new Label("Username:");

l2 = new Label("Password:");

l3 = new Label();

// TextFields

t1 = new TextField(20);

t2 = new TextField(20);

t2.setEchoChar('*');

// Buttons

bLogin = new Button("Login");


bClear = new Button("Clear");

// Set Layout

setLayout(new FlowLayout());

// Add components

add(l1);

add(t1);

add(l2);

add(t2);

add(bLogin);

add(bClear);

add(l3);

// Add ActionListeners

bLogin.addActionListener(this);

bClear.addActionListener(this);

// Frame settings

setTitle("Login Screen");

setSize(300, 200);

setVisible(true);

// Close window

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent we) {

System.exit(0);

});

}
public void actionPerformed(ActionEvent e) {

if (e.getSource() == bClear) {

t1.setText("");

t2.setText("");

l3.setText("");

} else if (e.getSource() == bLogin) {

try {

attempts++;

String user = t1.getText();

String pass = t2.getText();

if (!user.equals(pass)) {

throw new InvalidLoginException("Username and Password must be same!");

l3.setText("Login Successful!");

attempts = 0;

} catch (InvalidLoginException ex) {

l3.setText(ex.getMessage());

if (attempts >= 3) {

l3.setText("3 Attempts Over! Access Denied.");

bLogin.setEnabled(false);

public static void main(String[] args) {


new LoginAWT();

Slip 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.

class Continent {

String continent = "Asia";

class Country extends Continent {

String country = "India";

class State extends Country {

String state = "Maharashtra";

String place = "Pune";

void display() {

System.out.println("Place: " + place);

System.out.println("State: " + state);

System.out.println("Country: " + country);

System.out.println("Continent: " + continent);

}
public class MultilevelInheritance {

public static void main(String[] args) {

State s = new State();

s.display();

Output:- Place: Pune

State: Maharashtra

Country: India

Continent: Asia

Q2) Write a menu driven program to perform the following operations on multidimensional array
ie matrices :AdditionMultiplicationExit

import java.util.Scanner;

public class MatrixMenu {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int choice;

System.out.print("Enter number of rows: ");

int r = sc.nextInt();

System.out.print("Enter number of columns: ");

int c = sc.nextInt();

int[][] A = new int[r][c];


int[][] B = new int[r][c];

int[][] result = new int[r][c];

System.out.println("Enter elements of Matrix A:");

for (int i = 0; i < r; i++)

for (int j = 0; j < c; j++)

A[i][j] = sc.nextInt();

System.out.println("Enter elements of Matrix B:");

for (int i = 0; i < r; i++)

for (int j = 0; j < c; j++)

B[i][j] = sc.nextInt();

do {

System.out.println("\n--- Matrix Operations Menu ---");

System.out.println("1. Addition");

System.out.println("2. Multiplication");

System.out.println("3. Exit");

System.out.print("Enter your choice: ");

choice = sc.nextInt();

switch (choice) {

case 1:

// Matrix Addition

for (int i = 0; i < r; i++) {

for (int j = 0; j < c; j++) {

result[i][j] = A[i][j] + B[i][j];


}

System.out.println("Result of Addition:");

for (int i = 0; i < r; i++) {

for (int j = 0; j < c; j++) {

System.out.print(result[i][j] + " ");

System.out.println();

break;

case 2:

// Matrix Multiplication (only if valid)

if (r != c) {

System.out.println("Multiplication not possible for non-square matrices!");

break;

int[][] mul = new int[r][c];

for (int i = 0; i < r; i++) {

for (int j = 0; j < c; j++) {

mul[i][j] = 0;

for (int k = 0; k < c; k++) {

mul[i][j] += A[i][k] * B[k][j];

System.out.println("Result of Multiplication:");
for (int i = 0; i < r; i++) {

for (int j = 0; j < c; j++) {

System.out.print(mul[i][j] + " ");

System.out.println();

break;

case 3:

System.out.println("Exiting Program...");

break;

default:

System.out.println("Invalid choice! Try again.");

} while (choice != 3);

sc.close();

Output:- Enter number of rows: 2

Enter number of columns: 2

Enter elements of Matrix A:

12

34

Enter elements of Matrix B:

56
78

--- Matrix Operations Menu ---

1. Addition

2. Multiplication

3. Exit

Enter your choice: 1

Result of Addition:

68

10 12

--- Matrix Operations Menu ---

Enter your choice: 2

Result of Multiplication:

19 22

43 50

--- Matrix Operations Menu ---

Enter your choice: 3

Exiting Program...

Slip 6

Q1) Write a program to display the Employee(Empid, Empname, Empdesignation,


Empsal)information using toString().

class Employee {

int empId;

String empName;
String empDesignation;

double empSal;

// Constructor

Employee(int id, String name, String desig, double sal) {

empId = id;

empName = name;

empDesignation = desig;

empSal = sal;

// Overriding toString() method

public String toString() {

return "Employee ID: " + empId +

"\nEmployee Name: " + empName +

"\nDesignation: " + empDesignation +

"\nSalary: " + empSal;

public class EmployeeInfo {

public static void main(String[] args) {

Employee e1 = new Employee(101, "Rahul", "Manager", 55000);

Employee e2 = new Employee(102, "Sneha", "Developer", 45000);

System.out.println(e1);

System.out.println("\n" + e2);
}

Output:- Employee ID: 101

Employee Name: Rahul

Designation: Manager

Salary: 55000.0

Employee ID: 102

Employee Name: Sneha

Designation: Developer

Salary: 45000.0

Q2) Create an abstract class “order” having members id, description. Create two subclasses
“PurchaseOrder” and “Sales Order” having members customer name and Vendor name
respectively. Definemethods accept and display in all cases. Create 3 objects each of Purchase
Order and Sales Order and accept and display details.

import java.util.Scanner;

// Abstract class

abstract class Order {

int id;

String description;

abstract void accept();

abstract void display();

// Subclass 1 - Purchase Order

class PurchaseOrder extends Order {


String customerName;

void accept() {

Scanner sc = new Scanner(System.in);

System.out.print("Enter Purchase Order ID: ");

id = sc.nextInt();

sc.nextLine(); // consume newline

System.out.print("Enter Description: ");

description = sc.nextLine();

System.out.print("Enter Customer Name: ");

customerName = sc.nextLine();

void display() {

System.out.println("\n--- Purchase Order Details ---");

System.out.println("Order ID: " + id);

System.out.println("Description: " + description);

System.out.println("Customer Name: " + customerName);

// Subclass 2 - Sales Order

class SalesOrder extends Order {

String vendorName;

void accept() {

Scanner sc = new Scanner(System.in);


System.out.print("Enter Sales Order ID: ");

id = sc.nextInt();

sc.nextLine(); // consume newline

System.out.print("Enter Description: ");

description = sc.nextLine();

System.out.print("Enter Vendor Name: ");

vendorName = sc.nextLine();

void display() {

System.out.println("\n--- Sales Order Details ---");

System.out.println("Order ID: " + id);

System.out.println("Description: " + description);

System.out.println("Vendor Name: " + vendorName);

// Main class

public class OrderMain {

public static void main(String[] args) {

PurchaseOrder[] po = new PurchaseOrder[3];

SalesOrder[] so = new SalesOrder[3];

System.out.println("Enter details for 3 Purchase Orders:");

for (int i = 0; i < 3; i++) {

po[i] = new PurchaseOrder();

po[i].accept();
}

System.out.println("\nEnter details for 3 Sales Orders:");

for (int i = 0; i < 3; i++) {

so[i] = new SalesOrder();

so[i].accept();

System.out.println("\n==== Purchase Orders ====");

for (int i = 0; i < 3; i++) {

po[i].display();

System.out.println("\n==== Sales Orders ====");

for (int i = 0; i < 3; i++) {

so[i].display();

Output:- Enter details for 3 Purchase Orders:

Enter Purchase Order ID: 101

Enter Description: Laptop Purchase

Enter Customer Name: Rohan

Enter Purchase Order ID: 102

Enter Description: Furniture Purchase

Enter Customer Name: Neha


Enter Purchase Order ID: 103

Enter Description: Stationery Purchase

Enter Customer Name: Aman

Enter details for 3 Sales Orders:

Enter Sales Order ID: 201

Enter Description: Laptop Sale

Enter Vendor Name: Dell

Enter Sales Order ID: 202

Enter Description: Furniture Sale

Enter Vendor Name: IKEA

Enter Sales Order ID: 203

Enter Description: Stationery Sale

Enter Vendor Name: Amazon

==== Purchase Orders ====

--- Purchase Order Details ---

Order ID: 101

Description: Laptop Purchase

Customer Name: Rohan

...

==== Sales Orders ====

--- Sales Order Details ---


Order ID: 201

Description: Laptop Sale

Vendor Name: Dell

Slip 7

Q1) Design a class for Bank. Bank Class should support following operations; a. Deposit a
certain amount into an accountb. Withdraw a certain amount from an accountc. Return a
Balance value specifying the amount with details

import java.util.Scanner;

class Bank {

int accNo;

String accName;

double balance;

// Constructor

Bank(int no, String name, double bal) {

accNo = no;

accName = name;

balance = bal;

// Deposit method

void deposit(double amount) {

balance += amount;

System.out.println("Deposited: " + amount);


}

// Withdraw method

void withdraw(double amount) {

if (amount > balance) {

System.out.println("Insufficient Balance!");

} else {

balance -= amount;

System.out.println("Withdrawn: " + amount);

// Display balance

void displayBalance() {

System.out.println("\n--- Account Details ---");

System.out.println("Account No: " + accNo);

System.out.println("Account Holder: " + accName);

System.out.println("Current Balance: " + balance);

public class BankMain {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter Account No: ");

int no = sc.nextInt();

sc.nextLine();
System.out.print("Enter Account Holder Name: ");

String name = sc.nextLine();

System.out.print("Enter Initial Balance: ");

double bal = sc.nextDouble();

Bank b = new Bank(no, name, bal);

int choice;

do {

System.out.println("\n--- Bank Menu ---");

System.out.println("1. Deposit");

System.out.println("2. Withdraw");

System.out.println("3. Display Balance");

System.out.println("4. Exit");

System.out.print("Enter your choice: ");

choice = sc.nextInt();

switch (choice) {

case 1:

System.out.print("Enter amount to deposit: ");

double dep = sc.nextDouble();

b.deposit(dep);

break;

case 2:

System.out.print("Enter amount to withdraw: ");

double wd = sc.nextDouble();

b.withdraw(wd);
break;

case 3:

b.displayBalance();

break;

case 4:

System.out.println("Thank you for banking with us!");

break;

default:

System.out.println("Invalid choice!");

} while (choice != 4);

sc.close();

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.*;

import java.util.Scanner;

public class FileReverseCase {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter file name (with path if needed): ");

String fileName = sc.nextLine();


try {

// Read the file content

FileReader fr = new FileReader(fileName);

BufferedReader br = new BufferedReader(fr);

StringBuilder content = new StringBuilder();

String line;

while ((line = br.readLine()) != null) {

content.append(line).append("\n");

br.close();

// Reverse the content

content.reverse();

// Change the case of each character

StringBuilder modified = new StringBuilder();

for (int i = 0; i < content.length(); i++) {

char ch = content.charAt(i);

if (Character.isUpperCase(ch))

modified.append(Character.toLowerCase(ch));

else if (Character.isLowerCase(ch))

modified.append(Character.toUpperCase(ch));

else

modified.append(ch);

}
// Display modified content

System.out.println("\n--- Modified Content ---");

System.out.println(modified);

} catch (IOException e) {

System.out.println("Error reading file: " + e.getMessage());

sc.close();

Output:- Hello World

Java Program

--- Modified Content ---

MARGORp AVAj

DLROw OLLEh

Slip 8

Q1) Create a class Sphere, to calculate the volume and surface area of sphere. (Hint : Surface
area=4*3.14(r*r), Volume=(4/3)3.14(r*r*r))

class Sphere {

double radius;

// Constructor

Sphere(double r) {

radius = r;
}

// Method to calculate surface area

double surfaceArea() {

return 4 * 3.14 * radius * radius;

// Method to calculate volume

double volume() {

return (4.0 / 3) * 3.14 * radius * radius * radius;

// Main method

public static void main(String[] args) {

Sphere s = new Sphere(5); // Example radius

System.out.println("Radius: " + s.radius);

System.out.println("Surface Area: " + s.surfaceArea());

System.out.println("Volume: " + s.volume());

Output:- Radius: 5.0

Surface Area: 314.0

Volume: 523.3333333333334
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 java.awt.*;

import java.awt.event.*;

public class MouseEventDemo extends Frame implements MouseListener, MouseMotionListener {

TextField tf;

// Constructor

MouseEventDemo() {

// Frame setup

setSize(400, 300);

setLayout(new FlowLayout());

setTitle("Mouse Event Demo");

// TextField to display mouse click position

tf = new TextField(30);

add(tf);

// Add mouse listeners

addMouseListener(this);

addMouseMotionListener(this);

setVisible(true);

// MouseListener methods
public void mouseClicked(MouseEvent e) {

tf.setText("Mouse Clicked at: (" + e.getX() + ", " + e.getY() + ")");

public void mousePressed(MouseEvent e) {}

public void mouseReleased(MouseEvent e) {}

public void mouseEntered(MouseEvent e) {}

public void mouseExited(MouseEvent e) {}

// MouseMotionListener methods

public void mouseMoved(MouseEvent e) {

setTitle("Mouse Moved to: (" + e.getX() + ", " + e.getY() + ")");

public void mouseDragged(MouseEvent e) {}

// Main method

public static void main(String[] args) {

new MouseEventDemo();

Slip 9

Q1) Define a “Clock” class that does the following ; a. Accept Hours, Minutes and Secondsb.
Check the validity of numbersc. Set the time to AM/PM modeUse the necessary constructors and
methods to do the above task
class Clock {

private int hours;

private int minutes;

private int seconds;

private String period; // AM or PM

// Constructor

Clock(int h, int m, int s) {

if (isValid(h, m, s)) {

hours = h;

minutes = m;

seconds = s;

setPeriod(); // set AM/PM

} else {

System.out.println("Invalid time! Setting default 12:00:00 AM");

hours = 12;

minutes = 0;

seconds = 0;

period = "AM";

// Method to check validity

private boolean isValid(int h, int m, int s) {

return (h >= 0 && h < 24) && (m >= 0 && m < 60) && (s >= 0 && s < 60);

}
// Method to set AM/PM

private void setPeriod() {

if (hours >= 12) {

period = "PM";

} else {

period = "AM";

// Convert to 12-hour format

hours = hours % 12;

if (hours == 0) hours = 12;

// Display time

public void displayTime() {

System.out.printf("Time: %02d:%02d:%02d %s\n", hours, minutes, seconds, period);

// Main method for testing

public static void main(String[] args) {

Clock c1 = new Clock(14, 30, 45); // 2:30:45 PM

c1.displayTime();

Clock c2 = new Clock(25, 10, 10); // Invalid, will set default

c2.displayTime();

}
Q2) Write a program to using marker interface create a class Product (product_id,
product_name, product_cost, product_quantity) default and parameterized constructor. Create
objectsof class product and display the contents of each object and Also display the object
count.

// Marker Interface

interface ProductMarker {

// Marker interface has no methods

// Product Class

class Product implements ProductMarker {

int product_id;

String product_name;

double product_cost;

int product_quantity;

// Static variable to count objects

static int objectCount = 0;

// Default Constructor

Product() {

product_id = 0;

product_name = "Unknown";

product_cost = 0.0;

product_quantity = 0;

objectCount++;

}
// Parameterized Constructor

Product(int id, String name, double cost, int quantity) {

product_id = id;

product_name = name;

product_cost = cost;

product_quantity = quantity;

objectCount++;

// Method to display product details

void display() {

System.out.println("Product ID: " + product_id);

System.out.println("Product Name: " + product_name);

System.out.println("Product Cost: $" + product_cost);

System.out.println("Product Quantity: " + product_quantity);

System.out.println("-------------------------------");

// Main method

public static void main(String[] args) {

// Creating objects

Product p1 = new Product(); // default

Product p2 = new Product(101, "Laptop", 850.50, 10);

Product p3 = new Product(102, "Mobile", 500.00, 25);

// Display product details

p1.display();
p2.display();

p3.display();

// Display object count

System.out.println("Total Product Objects Created: " + Product.objectCount);

Output:-Product ID: 0

Product Name: Unknown

Product Cost: $0.0

Product Quantity: 0

-------------------------------

Product ID: 101

Product Name: Laptop

Product Cost: $850.5

Product Quantity: 10

-------------------------------

Product ID: 102

Product Name: Mobile

Product Cost: $500.0

Product Quantity: 25

-------------------------------

Total Product Objects Created: 3

Slip 10

Q1) Write a program to find the cube of given number using functional interface.

// Functional Interface

@FunctionalInterface

interface CubeCalculator {

int calculate(int x); // abstract method


}

public class CubeFunctional {

public static void main(String[] args) {

// Lambda expression to implement the functional interface

CubeCalculator cube = (x) -> x * x * x;

int number = 5; // Example number

int result = cube.calculate(number);

System.out.println("Cube of " + number + " is: " + result);

Output:- Cube of 5 is: 125

Q2) Write a program to create a package name student. Define class StudentInfo with method
todisplay information about student such as rollno, class, and percentage. Create another
classStudentPer with method to find percentage of the student. Accept student details likerollno,
name, class and marks of 6 subject from user

// studentinfo create flie type program

package student;

public class StudentInfo {

int rollNo;

String name;

String className;

// Constructor
public StudentInfo(int rollNo, String name, String className) {

this.rollNo = rollNo;

this.name = name;

this.className = className;

// Method to display student information

public void displayInfo(double percentage) {

System.out.println("Roll No: " + rollNo);

System.out.println("Name: " + name);

System.out.println("Class: " + className);

System.out.println("Percentage: " + percentage + "%");

System.out.println("---------------------------");

// studentper create flie type program

package student;

public class StudentPer {

// Method to calculate percentage from marks array

public double calculatePercentage(int[] marks) {

int total = 0;

for (int m : marks) {

total += m;

return (total / (marks.length * 100.0)) * 100; // percentage

} }
// main file create and type program

import student.StudentInfo;

import student.StudentPer;

import java.util.Scanner;

public class MainStudent {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Accept student basic details

System.out.print("Enter Roll No: ");

int rollNo = sc.nextInt();

sc.nextLine(); // consume newline

System.out.print("Enter Name: ");

String name = sc.nextLine();

System.out.print("Enter Class: ");

String className = sc.nextLine();

// Accept marks for 6 subjects

int[] marks = new int[6];

System.out.println("Enter marks of 6 subjects: ");

for (int i = 0; i < 6; i++) {

marks[i] = sc.nextInt();

// Create objects

StudentInfo sInfo = new StudentInfo(rollNo, name, className);


StudentPer sPer = new StudentPer();

// Calculate percentage

double percentage = sPer.calculatePercentage(marks);

// Display information

sInfo.displayInfo(percentage);

Output:- Roll No: 101

Name: John

Class: 10th

Marks: 80 75 90 85 70 95

Slip 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

double volume(); // abstract method

// Class Cylinder implementing Operation

class Cylinder implements Operation {

double radius;

double height;
// Constructor

Cylinder(double r, double h) {

radius = r;

height = h;

// Implement volume method

public double volume() {

return PI * radius * radius * height;

// Main method

public static void main(String[] args) {

Cylinder c = new Cylinder(5, 10); // Example radius=5, height=10

System.out.println("Volume of Cylinder: " + c.volume());

Output:- Volume of Cylinder: 785.5

Q2) Write a program to accept the username and password from user if username and password
arenot same then raise "Invalid Password" with appropriate msg.

import java.util.Scanner;

// Custom Exception

class InvalidPasswordException extends Exception {

public InvalidPasswordException(String msg) {


super(msg);

public class UserLogin {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Accept username and password

System.out.print("Enter username: ");

String username = sc.nextLine();

System.out.print("Enter password: ");

String password = sc.nextLine();

try {

// Check if username and password are the same

if (!username.equals(password)) {

throw new InvalidPasswordException("Invalid Password! Password must be same as


username.");

System.out.println("Login Successful!");

} catch (InvalidPasswordException e) {

System.out.println(e.getMessage());

}
Output:- Enter username: John

Enter password: 1234

Invalid Password! Password must be same as username.

Enter username: John

Enter password: John

Login Successful

Slip 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.

// Parent class College

class College {

int cno;

String cname;

String caddr;

// Constructor

College(int cno, String cname, String caddr) {

this.cno = cno;

this.cname = cname;

this.caddr = caddr;

// Method to display college details

void displayCollege() {

System.out.println("College No: " + cno);

System.out.println("College Name: " + cname);


System.out.println("College Address: " + caddr);

// Derived class Department

class Department extends College {

int dno;

String dname;

// Constructor

Department(int cno, String cname, String caddr, int dno, String dname) {

super(cno, cname, caddr); // call parent constructor

this.dno = dno;

this.dname = dname;

// Method to display department details

void displayDepartment() {

displayCollege(); // call parent method

System.out.println("Department No: " + dno);

System.out.println("Department Name: " + dname);

// Main method

public static void main(String[] args) {

Department dept = new Department(101, "ABC College", "New York", 1, "Computer


Science");
dept.displayDepartment();

Q2) Write a java program that works as a simple calculator. Use a grid layout to arrange buttons
forthe digits and for the +, -, *, % operations. Add a text field to display the result.

[Calculator diagram]

import java.awt.*;

import java.awt.event.*;

public class SimpleCalculator extends Frame implements ActionListener {

TextField tf;

String operator = "";

double num1 = 0, num2 = 0;

// Constructor

SimpleCalculator() {

setTitle("Simple Calculator");

setSize(300, 400);

setLayout(new BorderLayout());

// TextField at the top

tf = new TextField();

add(tf, BorderLayout.NORTH);

// Panel for buttons with GridLayout

Panel panel = new Panel();

panel.setLayout(new GridLayout(4, 4, 5, 5));


// Buttons

String[] buttons = {

"1", "2", "3", "+",

"4", "5", "6", "-",

"7", "8", "9", "*",

"0", ".", "=", "/"

};

for (String b : buttons) {

Button btn = new Button(b);

btn.addActionListener(this);

panel.add(btn);

add(panel, BorderLayout.CENTER);

// Close window properly

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent we) {

dispose();

System.exit(0);

});

setVisible(true);

}
// Handle button clicks

public void actionPerformed(ActionEvent e) {

String str = e.getActionCommand();

if (str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/")) {

num1 = Double.parseDouble(tf.getText());

operator = str;

tf.setText("");

} else if (str.equals("=")) {

num2 = Double.parseDouble(tf.getText());

double result = 0;

switch (operator) {

case "+": result = num1 + num2; break;

case "-": result = num1 - num2; break;

case "*": result = num1 * num2; break;

case "/":

if(num2 != 0) result = num1 / num2;

else { tf.setText("Error"); return; }

break;

tf.setText(String.valueOf(result));

} else {

tf.setText(tf.getText() + str);

}
// Main method

public static void main(String[] args) {

new SimpleCalculator();

Slip 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.*;

public class FileCount {

public static void main(String[] args) {

if (args.length != 1) {

System.out.println("Usage: java FileCount <filename>");

return;

String fileName = args[0];

File file = new File(fileName);

if (!file.exists()) {

System.out.println("File does not exist!");

return;

int lineCount = 0;
int wordCount = 0;

try (BufferedReader br = new BufferedReader(new FileReader(file))) {

String line;

while ((line = br.readLine()) != null) {

lineCount++;

String[] words = line.trim().split("\\s+");

if (words.length > 0 && !words[0].equals("")) {

wordCount += words.length;

System.out.println("Number of lines: " + lineCount);

System.out.println("Number of words: " + wordCount);

} catch (IOException e) {

System.out.println("Error reading file: " + e.getMessage());

Output:- Number of lines: 5

Number of words: 28

Q2) Write a program to display the system date and time in various formats shown below:Current
date is : 31/08/2021Current date is : 08-31-2021Current date is : Tuesday August 31 2021Current
date and time is : Fri August 31 15:25:59 IST 2021Current date and time is : 31/08/21 15:25:59 PM
+0530

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormats {

public static void main(String[] args) {

Date now = new Date();

SimpleDateFormat f1 = new SimpleDateFormat("dd/MM/yyyy");

SimpleDateFormat f2 = new SimpleDateFormat("MM-dd-yyyy");

SimpleDateFormat f3 = new SimpleDateFormat("EEEE MMMM dd yyyy");

SimpleDateFormat f4 = new SimpleDateFormat("EEE MMMM dd HH:mm:ss z yyyy");

SimpleDateFormat f5 = new SimpleDateFormat("dd/MM/yy HH:mm:ss a Z");

System.out.println("Current date is : " + f1.format(now));

System.out.println("Current date is : " + f2.format(now));

System.out.println("Current date is : " + f3.format(now));

System.out.println("Current date and time is : " + f4.format(now));

System.out.println("Current date and time is : " + f5.format(now));

Slip 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;

// User-defined exception
class NumberIsZeroException extends Exception {

public NumberIsZeroException(String message) {

super(message);

public class PrimeCheck {

// Static method to check prime

public static boolean isPrime(int num) {

if (num <= 1) return false;

for (int i = 2; i <= num / 2; i++) {

if (num % i == 0)

return false;

return true;

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter a number: ");

int num = sc.nextInt();

try {

if (num == 0)

throw new NumberIsZeroException("Number is 0");

if (isPrime(num))
System.out.println(num + " is a Prime Number");

else

System.out.println(num + " is Not a Prime Number");

} catch (NumberIsZeroException e) {

System.out.println(e.getMessage());

Output:- Enter a number: 7

7 is a Prime Number

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.

// create file SY

package SY;

public class SYMarks {

public int ComputerTotal;

public int MathsTotal;

public int ElectronicsTotal;

public SYMarks(int c, int m, int e) {

ComputerTotal = c;

MathsTotal = m;
ElectronicsTotal = e;

// TY file

package TY;

public class TYMarks {

public int Theory;

public int Practicals;

public TYMarks(int t, int p) {

Theory = t;

Practicals = p;

// main class student result

import SY.SYMarks;

import TY.TYMarks;

import java.util.Scanner;

class Student {

int rollNumber;

String name;

SYMarks sy;

TYMarks ty;

Student(int roll, String n, SYMarks s, TYMarks t) {


rollNumber = roll;

name = n;

sy = s;

ty = t;

void calculateGrade() {

double total = sy.ComputerTotal + ty.Theory + ty.Practicals;

double avg = total / 3; // average of 3 parts (SY comp, TY theory, TY practical)

String grade;

if (avg >= 70) grade = "A";

else if (avg >= 60) grade = "B";

else if (avg >= 50) grade = "C";

else if (avg >= 40) grade = "Pass Class";

else grade = "FAIL";

System.out.println("Roll No: " + rollNumber);

System.out.println("Name : " + name);

System.out.println("SY Computer Marks: " + sy.ComputerTotal);

System.out.println("TY Theory Marks : " + ty.Theory);

System.out.println("TY Practical Marks: " + ty.Practicals);

System.out.println("Average: " + avg);

System.out.println("Grade : " + grade);

System.out.println("---------------------------------");

}
public class StudentResult {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter number of students: ");

int n = sc.nextInt();

Student[] students = new Student[n];

for (int i = 0; i < n; i++) {

System.out.println("\nEnter details for Student " + (i + 1));

System.out.print("Roll Number: ");

int roll = sc.nextInt();

sc.nextLine(); // consume newline

System.out.print("Name: ");

String name = sc.nextLine();

System.out.print("Enter SY Computer, Maths, Electronics marks: ");

int c = sc.nextInt(), m = sc.nextInt(), e = sc.nextInt();

System.out.print("Enter TY Theory and Practical marks: ");

int t = sc.nextInt(), p = sc.nextInt();

SYMarks sy = new SYMarks(c, m, e);

TYMarks ty = new TYMarks(t, p);


students[i] = new Student(roll, name, sy, ty);

System.out.println("\n---------- Student Results ----------");

for (Student s : students)

s.calculateGrade();

Slip 15

Q1) Accept the names of two files and copy the contents of the first to the second. First file
havingBook name and Author name in file.

import java.io.*;

import java.util.Scanner;

public class CopyFile {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter source file name: ");

String sourceFile = sc.nextLine();

System.out.print("Enter destination file name: ");

String destFile = sc.nextLine();

File src = new File(sourceFile);


File dest = new File(destFile);

if (!src.exists()) {

System.out.println("Source file does not exist!");

return;

try (BufferedReader br = new BufferedReader(new FileReader(src));

BufferedWriter bw = new BufferedWriter(new FileWriter(dest))) {

String line;

while ((line = br.readLine()) != null) {

bw.write(line);

bw.newLine(); // move to next line

System.out.println("File copied successfully!");

} catch (IOException e) {

System.out.println("Error: " + e.getMessage());

Output:- Book: The Alchemist

Author: Paulo Coelho----------->

Enter source file name: book.txt

Enter destination file name: copy.txt------------------------> File copied successfully!


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.

// Q2) Account class with inheritance

class Account {

String custName;

int accNo;

// Default constructor

Account() {

custName = "Unknown";

accNo = 0;

// Parameterized constructor

Account(String name, int no) {

custName = name;

accNo = no;

// Subclass SavingAccount

class SavingAccount extends Account {

double savingBal;

double minBal;
SavingAccount() {

super();

savingBal = 0.0;

minBal = 500.0;

SavingAccount(String name, int no, double bal, double min) {

super(name, no);

savingBal = bal;

minBal = min;

// Derived class AccountDetail

class AccountDetail extends SavingAccount {

double depositAmt;

double withdrawalAmt;

AccountDetail(String name, int no, double bal, double min, double dep, double with) {

super(name, no, bal, min);

depositAmt = dep;

withdrawalAmt = with;

void displayDetails() {

double newBal = (savingBal + depositAmt) - withdrawalAmt;

System.out.println("----- Customer Account Details -----");


System.out.println("Customer Name : " + custName);

System.out.println("Account No : " + accNo);

System.out.println("Saving Balance: " + savingBal);

System.out.println("Minimum Balance: " + minBal);

System.out.println("Deposit Amount : " + depositAmt);

System.out.println("Withdrawal Amt : " + withdrawalAmt);

System.out.println("New Balance : " + newBal);

System.out.println("------------------------------------");

// Main class

public class AccountMain {

public static void main(String[] args) {

AccountDetail a1 = new AccountDetail("Riya Patil", 12345, 10000, 500, 2000, 1500);

a1.displayDetails();

Slip 16

Q1) Write a program to find the Square of given number using function interface.

import java.util.Scanner;

// Functional interface

@FunctionalInterface

interface Square {

int calculate(int x);


}

public class SquareNumber {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter a number: ");

int num = sc.nextInt();

// Lambda expression to define the function

Square sq = (x) -> x * x;

System.out.println("Square of " + num + " is: " + sq.calculate(num));

Q2) Write a program to design a screen using Awt that,

[[Diagram file, new,open,save type table ]]

import java.awt.*;

import java.awt.event.*;

public class MenuExample extends Frame {

MenuExample() {

// Create Menu Bar

MenuBar mb = new MenuBar();

// Create Menus

Menu file = new Menu("File");


Menu edit = new Menu("Edit");

Menu about = new Menu("About");

// Create Menu Items

MenuItem newItem = new MenuItem("New");

MenuItem open = new MenuItem("Open");

MenuItem save = new MenuItem("Save");

CheckboxMenuItem showAbout = new CheckboxMenuItem("Show About");

MenuItem exit = new MenuItem("Exit");

// Add items to File menu

file.add(newItem);

file.add(open);

file.add(save);

file.addSeparator();

file.add(showAbout);

file.addSeparator();

file.add(exit);

// Add menus to Menu Bar

mb.add(file);

mb.add(edit);

mb.add(about);

// Set Menu Bar

setMenuBar(mb);
// Add window closing event

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent we) {

System.exit(0);

});

setTitle("Java AWT Examples");

setSize(400, 300);

setVisible(true);

public static void main(String[] args) {

new MenuExample();

Slip 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;

// Super class

class Customer {

String name;
String phoneNumber;

void readCustomer(Scanner sc) {

System.out.print("Enter Customer Name: ");

name = sc.nextLine();

System.out.print("Enter Phone Number: ");

phoneNumber = sc.nextLine();

void displayCustomer() {

System.out.println("Name : " + name);

System.out.println("Phone Number : " + phoneNumber);

// Derived class from Customer

class Depositor extends Customer {

int accNo;

double balance;

void readDepositor(Scanner sc) {

System.out.print("Enter Account Number: ");

accNo = sc.nextInt();

System.out.print("Enter Balance: ");

balance = sc.nextDouble();

sc.nextLine(); // consume newline

}
void displayDepositor() {

System.out.println("Account Number : " + accNo);

System.out.println("Balance : " + balance);

// Derived class from Depositor

class Borrower extends Depositor {

int loanNo;

double loanAmt;

void readBorrower(Scanner sc) {

System.out.print("Enter Loan Number: ");

loanNo = sc.nextInt();

System.out.print("Enter Loan Amount: ");

loanAmt = sc.nextDouble();

sc.nextLine(); // consume newline

void displayBorrower() {

System.out.println("Loan Number : " + loanNo);

System.out.println("Loan Amount : " + loanAmt);

void readAll(Scanner sc) {

readCustomer(sc);
readDepositor(sc);

readBorrower(sc);

void displayAll() {

System.out.println("----------------------------------");

displayCustomer();

displayDepositor();

displayBorrower();

// Main class

public class CustomerDetails {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter number of customers: ");

int n = sc.nextInt();

sc.nextLine(); // consume newline

Borrower[] b = new Borrower[n];

for (int i = 0; i < n; i++) {

System.out.println("\nEnter details for Customer " + (i + 1));

b[i] = new Borrower();

b[i].readAll(sc);

}
System.out.println("\n========== Customer Details ==========");

for (int i = 0; i < n; i++) {

b[i].displayAll();

Q2) Write Java program to design three text boxes and two buttons using swing. Enter different
strings in first and second textbox. On clicking the First command button, concatenation of two
strings should be displayed in third text box and on clicking second command button, reverse of
string should display in third text box

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class StringOperations extends JFrame implements ActionListener {

JTextField txt1, txt2, txt3;

JButton btnConcat, btnReverse;

public StringOperations() {

setTitle("String Operations");

setSize(400, 250);

setLayout(new FlowLayout());

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel l1 = new JLabel("First String:");

JLabel l2 = new JLabel("Second String:");


JLabel l3 = new JLabel("Result:");

txt1 = new JTextField(20);

txt2 = new JTextField(20);

txt3 = new JTextField(20);

txt3.setEditable(false);

btnConcat = new JButton("Concatenate");

btnReverse = new JButton("Reverse");

add(l1);

add(txt1);

add(l2);

add(txt2);

add(l3);

add(txt3);

add(btnConcat);

add(btnReverse);

btnConcat.addActionListener(this);

btnReverse.addActionListener(this);

setVisible(true);

public void actionPerformed(ActionEvent e) {

String s1 = txt1.getText();
String s2 = txt2.getText();

if (e.getSource() == btnConcat) {

txt3.setText(s1 + s2);

} else if (e.getSource() == btnReverse) {

String rev = new StringBuilder(s1 + s2).reverse().toString();

txt3.setText(rev);

public static void main(String[] args) {

new StringOperations();

Q2) Write Java program to design three text boxes and two buttons using swing. Enter different
strings in first and second textbox. On clicking the First command button, concatenation of two
strings should be displayed in third text box and on clicking second command button, reverse of
string should display in third text box

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class StringOperations extends JFrame implements ActionListener {

JTextField txt1, txt2, txt3;

JButton btnConcat, btnReverse;

public StringOperations() {
setTitle("String Operations");

setSize(400, 250);

setLayout(new FlowLayout());

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel l1 = new JLabel("First String:");

JLabel l2 = new JLabel("Second String:");

JLabel l3 = new JLabel("Result:");

txt1 = new JTextField(20);

txt2 = new JTextField(20);

txt3 = new JTextField(20);

txt3.setEditable(false);

btnConcat = new JButton("Concatenate");

btnReverse = new JButton("Reverse");

add(l1);

add(txt1);

add(l2);

add(txt2);

add(l3);

add(txt3);

add(btnConcat);

add(btnReverse);

btnConcat.addActionListener(this);
btnReverse.addActionListener(this);

setVisible(true);

public void actionPerformed(ActionEvent e) {

String s1 = txt1.getText();

String s2 = txt2.getText();

if (e.getSource() == btnConcat) {

txt3.setText(s1 + s2);

} else if (e.getSource() == btnReverse) {

String rev = new StringBuilder(s1 + s2).reverse().toString();

txt3.setText(rev);

public static void main(String[] args) {

new StringOperations();

Slip 18

Q1) Write a program to implement Border Layout Manager.

import java.awt.*;

import java.awt.event.*;
public class BorderLayoutExample {

public static void main(String[] args) {

// Create a new frame

Frame f = new Frame("BorderLayout Example");

// Set BorderLayout for the frame

f.setLayout(new BorderLayout());

// Create buttons for different regions

Button b1 = new Button("North");

Button b2 = new Button("South");

Button b3 = new Button("East");

Button b4 = new Button("West");

Button b5 = new Button("Center");

// Add buttons to the frame

f.add(b1, BorderLayout.NORTH);

f.add(b2, BorderLayout.SOUTH);

f.add(b3, BorderLayout.EAST);

f.add(b4, BorderLayout.WEST);

f.add(b5, BorderLayout.CENTER);

// Set frame size and make it visible

f.setSize(400, 400);

f.setVisible(true);
// Close window properly on clicking the close button

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent we) {

f.dispose();

});

Q2) Define a class CricketPlayer (name,no_of_innings,no_of_times_notout, totatruns, bat_avg).


Create an array of n player objects. Calculate the batting average for each player using static
method avg(). Define a static sort method which sorts the array on the basis of average. Display
the player details in sorted order.

import java.util.Scanner;

import java.util.Arrays;

class CricketPlayer {

String name;

int no_of_innings;

int no_of_times_notout;

int totalRuns;

double bat_avg;

// Constructor

CricketPlayer(String name, int innings, int notOut, int runs) {

this.name = name;

this.no_of_innings = innings;

this.no_of_times_notout = notOut;
this.totalRuns = runs;

this.bat_avg = 0.0;

// Static method to calculate batting average

static void avg(CricketPlayer player) {

if (player.no_of_innings - player.no_of_times_notout != 0)

player.bat_avg = (double) player.totalRuns / (player.no_of_innings -


player.no_of_times_notout);

else

player.bat_avg = player.totalRuns; // avoid division by zero

// Static method to sort players based on batting average in descending order

static void sort(CricketPlayer[] players) {

Arrays.sort(players, (p1, p2) -> Double.compare(p2.bat_avg, p1.bat_avg));

// Method to display player details

void display() {

System.out.println(name + "\t" + no_of_innings + "\t" + no_of_times_notout + "\t" + totalRuns


+ "\t" + bat_avg);

public class CricketPlayerDemo {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


System.out.print("Enter number of players: ");

int n = sc.nextInt();

sc.nextLine(); // consume newline

CricketPlayer[] players = new CricketPlayer[n];

// Input details for each player

for (int i = 0; i < n; i++) {

System.out.println("Enter details for player " + (i + 1) + ":");

System.out.print("Name: ");

String name = sc.nextLine();

System.out.print("Number of innings: ");

int innings = sc.nextInt();

System.out.print("Number of times not out: ");

int notOut = sc.nextInt();

System.out.print("Total runs: ");

int runs = sc.nextInt();

sc.nextLine(); // consume newline

players[i] = new CricketPlayer(name, innings, notOut, runs);

CricketPlayer.avg(players[i]); // calculate average

// Sort players by batting average

CricketPlayer.sort(players);
// Display player details

System.out.println("\nPlayer Details in Sorted Order (by Batting Average):");

System.out.println("Name\tInnings\tNotOut\tRuns\tAvg");

for (CricketPlayer player : players) {

player.display();

sc.close();

Output:- Enter number of players: 3

Enter details for player 1:

Name: Virat

Number of innings: 10

Number of times not out: 2

Total runs: 500

Enter details for player 2:

Name: Rohit

Number of innings: 8

Number of times not out: 1

Total runs: 400

Enter details for player 3:

Name: Dhoni

Number of innings: 12

Number of times not out: 4

Total runs: 480

Slip 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 sc = new Scanner(System.in);

System.out.print("Enter number of rows: ");

int rows = sc.nextInt();

System.out.print("Enter number of columns: ");

int cols = sc.nextInt();

if (rows != cols) {

System.out.println("Matrix must be square to have a diagonal.");

return;

int[][] matrix = new int[rows][cols];

// Input matrix elements

System.out.println("Enter elements of the matrix:");

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

matrix[i][j] = sc.nextInt();

}
// Calculate sum of diagonal elements

int sum = 0;

for (int i = 0; i < rows; i++) {

sum += matrix[i][i]; // main diagonal

System.out.println("Sum of diagonal elements: " + sum);

sc.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.*;

public class SubjectComboBox {

public static void main(String[] args) {

// Create frame

JFrame frame = new JFrame("T.Y.B.Sc. Computer Science Subjects");

frame.setSize(400, 200);

frame.setLayout(new FlowLayout());

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Subjects array

String[] subjects = {

"Computer Networks",

"Operating Systems",

"Database Management System",

"Software Engineering",

"Artificial Intelligence"

};

// Create combo box

JComboBox<String> comboBox = new JComboBox<>(subjects);

// Create text field

JTextField textField = new JTextField(20);

textField.setEditable(false);

// Add action listener to combo box

comboBox.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

String selectedSubject = (String) comboBox.getSelectedItem();

textField.setText(selectedSubject);

});

// Add components to frame

frame.add(new JLabel("Select Subject:"));

frame.add(comboBox);
frame.add(new JLabel("Selected Subject:"));

frame.add(textField);

frame.setVisible(true);

Slip 20

Q1) Write a program to implement Border Layout Manager.

// Base class

class Continent {

String continentName;

void setContinent(String name) {

continentName = name;

void displayContinent() {

System.out.println("Continent: " + continentName);

// Country class inherits from Continent

class Country extends Continent {

String countryName;
void setCountry(String name) {

countryName = name;

void displayCountry() {

System.out.println("Country: " + countryName);

// State class inherits from Country

class State extends Country {

String stateName;

void setState(String name) {

stateName = name;

void displayState() {

System.out.println("State: " + stateName);

// Place class inherits from State

class Place extends State {

String placeName;
void setPlace(String name) {

placeName = name;

void displayPlace() {

System.out.println("Place: " + placeName);

// Main class

public class MultilevelInheritanceDemo {

public static void main(String[] args) {

Place p = new Place();

// Set values

p.setContinent("Asia");

p.setCountry("India");

p.setState("Maharashtra");

p.setPlace("Mumbai");

// Display values

p.displayContinent();

p.displayCountry();

p.displayState();

p.displayPlace();

} }

Output:-Continent: Asia , Country: India , State: Maharashtra , Place: Mumbai


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

Ans :- Step 1 create a package and classes

// addition. Java

package Operation;

public class Addition {

// Method to add two integers

public int add(int a, int b) {

return a + b;

// Method to subtract two float values

public float subtract(float a, float b) {

return a - b;

//maximum.java

package Operation;

public class Maximum {

// Method to find maximum of two integers

public int max(int a, int b) {

if (a > b)

return a;

else

return b;
}

Step 2 create a class to test the package

import Operation.Addition;

import Operation.Maximum;

public class TestOperation {

public static void main(String[] args) {

Addition addObj = new Addition();

Maximum maxObj = new Maximum();

// Using Addition methods

int sum = addObj.add(10, 20);

float diff = addObj.subtract(15.5f, 5.2f);

// Using Maximum method

int maximum = maxObj.max(10, 20);

// Display results

System.out.println("Sum of 10 and 20: " + sum);

System.out.println("Difference of 15.5 and 5.2: " + diff);

System.out.println("Maximum of 10 and 20: " + maximum);

Slip 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;

// User-defined Exception

class InvalidDateException extends Exception {

public InvalidDateException(String message) {

super(message);

// MyDate class

class MyDate {

private int day;

private int month;

private int year;

// Method to accept date

public void acceptDate() throws InvalidDateException {

Scanner sc = new Scanner(System.in);

System.out.print("Enter day: ");

day = sc.nextInt();

System.out.print("Enter month: ");

month = sc.nextInt();

System.out.print("Enter year: ");

year = sc.nextInt();
if (!isValidDate(day, month, year)) {

throw new InvalidDateException("Invalid Date! Please enter a valid date.");

// Method to display date

public void displayDate() {

System.out.println("Date is: " + day + "/" + month + "/" + year);

// Method to validate date

private boolean isValidDate(int d, int m, int y) {

if (y <= 0 || m <= 0 || m > 12 || d <= 0) return false;

int[] daysInMonth = { 31, 28, 31, 30, 31, 30,

31, 31, 30, 31, 30, 31 };

// Leap year check

if (m == 2 && isLeapYear(y)) {

if (d > 29) return false;

} else {

if (d > daysInMonth[m - 1]) return false;

return true;

}
private boolean isLeapYear(int y) {

return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);

// Main class

public class TestMyDate {

public static void main(String[] args) {

MyDate date = new MyDate();

try {

date.acceptDate();

date.displayDate();

} catch (InvalidDateException e) {

System.out.println(e.getMessage());

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.

// Employee class

class Employee {

private int id;

private String name;

private String deptName;

private double salary;


// Static member to keep count of objects

private static int count = 0;

// Default constructor

public Employee() {

this.id = 0;

this.name = "Unknown";

this.deptName = "Unknown";

this.salary = 0.0;

count++;

// Parameterized constructor

public Employee(int id, String name, String deptName, double salary) {

this.id = id;

this.name = name;

this.deptName = deptName;

this.salary = salary;

count++;

// Static method to get object count

public static int getObjectCount() {

return count;

}
// Method to display employee details

public void display() {

System.out.println("ID: " + id);

System.out.println("Name: " + name);

System.out.println("Department: " + deptName);

System.out.println("Salary: " + salary);

System.out.println("---------------------------");

// Main class

public class TestEmployee {

public static void main(String[] args) {

// Creating employee objects using parameterized constructor

Employee e1 = new Employee(101, "Alice", "IT", 50000);

e1.display();

System.out.println("Total Employees: " + Employee.getObjectCount() + "\n");

Employee e2 = new Employee(102, "Bob", "HR", 45000);

e2.display();

System.out.println("Total Employees: " + Employee.getObjectCount() + "\n");

Employee e3 = new Employee(103, "Charlie", "Finance", 60000);

e3.display();

System.out.println("Total Employees: " + Employee.getObjectCount() + "\n");

}
Slip 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).

import java.util.Scanner;

// Abstract class Shape

abstract class Shape {

protected int a, b; // Two integers for dimensions

// Abstract method

abstract void printArea();

// Rectangle class

class Rectangle extends Shape {

// Constructor to initialize sides

Rectangle(int length, int width) {

this.a = length;

this.b = width;

// Overriding printArea method

void printArea() {

int area = a * b;
System.out.println("Area of Rectangle: " + area);

// Triangle class

class Triangle extends Shape {

// Constructor to initialize base and height

Triangle(int base, int height) {

this.a = base;

this.b = height;

// Overriding printArea method

void printArea() {

double area = 0.5 * a * b;

System.out.println("Area of Triangle: " + area);

// Circle class

class Circle extends Shape {

// Constructor to initialize radius (using 'a' as radius)

Circle(int radius) {

this.a = radius;

}
// Overriding printArea method

void printArea() {

double area = 3.14159 * a * a;

System.out.println("Area of Circle: " + area);

// Main class

public class TestShape {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Rectangle

System.out.print("Enter length of rectangle: ");

int length = sc.nextInt();

System.out.print("Enter width of rectangle: ");

int width = sc.nextInt();

Shape r = new Rectangle(length, width);

r.printArea();

// Triangle

System.out.print("Enter base of triangle: ");

int base = sc.nextInt();

System.out.print("Enter height of triangle: ");

int height = sc.nextInt();

Shape t = new Triangle(base, height);


t.printArea();

// Circle

System.out.print("Enter radius of circle: ");

int radius = sc.nextInt();

Shape c = new Circle(radius);

c.printArea();

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 java.awt.*;

import java.awt.event.*;

class MouseEventsDemo extends Frame {

String msg = "";

public MouseEventsDemo() {

setSize(500, 400);

setTitle("Mouse Events Demo");

setVisible(true);

// Adding MouseAdapter for mouse events

addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) {

msg = "Mouse Clicked";


repaint();

public void mousePressed(MouseEvent e) {

msg = "Mouse Pressed";

repaint();

public void mouseReleased(MouseEvent e) {

msg = "Mouse Released";

repaint();

public void mouseEntered(MouseEvent e) {

msg = "Mouse Entered";

repaint();

public void mouseExited(MouseEvent e) {

msg = "Mouse Exited";

repaint();

});

addMouseMotionListener(new MouseAdapter() {

public void mouseDragged(MouseEvent e) {

msg = "Mouse Dragged";


repaint();

public void mouseMoved(MouseEvent e) {

msg = "Mouse Moved";

repaint();

});

// Closing window

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

dispose();

});

public void paint(Graphics g) {

g.setColor(Color.RED);

Font f = new Font("Arial", Font.BOLD, 20);

g.setFont(f);

// Draw message at center

g.drawString(msg, getWidth() / 2 - 70, getHeight() / 2);

public static void main(String[] args) {

new MouseEventsDemo();
}

Slip 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, isPositive, isZero, isOdd, isEven. Create an object in main.Use command line
arguments to pass a value to the Object

class MyNumber {

private int num;

// Default constructor

public MyNumber() {

this.num = 0;

// Parameterized constructor

public MyNumber(int num) {

this.num = num;

// Method to check if number is positive

public boolean isPositive() {

return num > 0;

// Method to check if number is negative


public boolean isNegative() {

return num < 0;

// Method to check if number is zero

public boolean isZero() {

return num == 0;

// Method to check if number is even

public boolean isEven() {

return num % 2 == 0;

// Method to check if number is odd

public boolean isOdd() {

return num % 2 != 0;

// Method to display number

public void display() {

System.out.println("Number: " + num);

System.out.println("Positive: " + isPositive());

System.out.println("Negative: " + isNegative());

System.out.println("Zero: " + isZero());

System.out.println("Even: " + isEven());

System.out.println("Odd: " + isOdd());


}

// Main class

public class TestMyNumber {

public static void main(String[] args) {

int value = 0;

if (args.length > 0) {

try {

value = Integer.parseInt(args[0]);

} catch (NumberFormatException e) {

System.out.println("Invalid input. Using 0 as default.");

MyNumber num = new MyNumber(value);

num.display();

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 SGD =
0.65 Euro.

Diagram [ currency convert .. Singapore dollars ;;;; us dollars ;;;;;; euros ]

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;
public class CurrencyConverter extends JFrame implements ActionListener {

JTextField sgdField, usdField, euroField;

// Conversion rates

final double USD_TO_SGD = 1.41;

final double USD_TO_EURO = 0.92;

final double SGD_TO_USD = 1 / USD_TO_SGD;

final double SGD_TO_EURO = 0.65;

final double EURO_TO_USD = 1 / USD_TO_EURO;

final double EURO_TO_SGD = 1 / SGD_TO_EURO;

public CurrencyConverter() {

setTitle("Currency Converter");

setLayout(new GridLayout(3, 2, 5, 5));

JLabel sgdLabel = new JLabel("Singapore Dollars:");

JLabel usdLabel = new JLabel("US Dollars:");

JLabel euroLabel = new JLabel("Euros:");

sgdField = new JTextField();

usdField = new JTextField();

euroField = new JTextField();

add(sgdLabel);

add(sgdField);

add(usdLabel);
add(usdField);

add(euroLabel);

add(euroField);

sgdField.addActionListener(this);

usdField.addActionListener(this);

euroField.addActionListener(this);

setSize(300, 150);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setVisible(true);

public void actionPerformed(ActionEvent e) {

try {

if (e.getSource() == sgdField) {

double sgd = Double.parseDouble(sgdField.getText());

double usd = sgd * SGD_TO_USD;

double euro = sgd * SGD_TO_EURO;

usdField.setText(String.format("%.2f", usd));

euroField.setText(String.format("%.2f", euro));

} else if (e.getSource() == usdField) {

double usd = Double.parseDouble(usdField.getText());

double sgd = usd * USD_TO_SGD;

double euro = usd * USD_TO_EURO;

sgdField.setText(String.format("%.2f", sgd));

euroField.setText(String.format("%.2f", euro));
} else if (e.getSource() == euroField) {

double euro = Double.parseDouble(euroField.getText());

double usd = euro * EURO_TO_USD;

double sgd = euro * EURO_TO_SGD;

usdField.setText(String.format("%.2f", usd));

sgdField.setText(String.format("%.2f", sgd));

} catch (NumberFormatException ex) {

JOptionPane.showMessageDialog(this, "Please enter a valid number!");

public static void main(String[] args) {

new CurrencyConverter();

Slip 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.

// Abstract class Bank

abstract class Bank {

// Abstract method

abstract int getBalance();


}

// BankA class

class BankA extends Bank {

int getBalance() {

return 100;

// BankB class

class BankB extends Bank {

int getBalance() {

return 150;

// BankC class

class BankC extends Bank {

int getBalance() {

return 200;

// Main class

public class TestBank {

public static void main(String[] args) {

Bank a = new BankA();


Bank b = new BankB();

Bank c = new BankC();

System.out.println("Balance in Bank A: Rs." + a.getBalance());

System.out.println("Balance in Bank B: Rs." + b.getBalance());

System.out.println("Balance in Bank C: Rs." + c.getBalance());

Output:- Balance in Bank A: Rs.100

Balance in Bank B: Rs.150

Balance in Bank C: Rs.200

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

[Diagram circle]

import java.awt.*;

import java.awt.event.*;

public class ConcentricCircles extends Frame implements MouseListener {

int x = -100, y = -100; // Initial values (off-screen)

// Constructor

ConcentricCircles() {

addMouseListener(this);

setSize(400, 400);

setTitle("Concentric Circles");
setVisible(true);

// Draw circles

public void paint(Graphics g) {

g.setColor(Color.red);

g.drawOval(x - 30, y - 30, 60, 60); // Outer circle

g.setColor(Color.blue);

g.drawOval(x - 20, y - 20, 40, 40); // Middle circle

g.setColor(Color.green);

g.drawOval(x - 10, y - 10, 20, 20); // Inner circle

// Mouse click event

public void mouseClicked(MouseEvent e) {

x = e.getX();

y = e.getY();

repaint();

// Unused methods

public void mousePressed(MouseEvent e) {}

public void mouseReleased(MouseEvent e) {}

public void mouseEntered(MouseEvent e) {}

public void mouseExited(MouseEvent e) {}

// Main method
public static void main(String[] args) {

ConcentricCircles cc = new ConcentricCircles();

cc.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent we) {

System.exit(0);

});

Slip 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.*;

// Student class

class Student {

private int rollNo;

private String name;

private String className;

private double per; // percentage

// Method to accept student details

public void accept() throws IOException {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));


System.out.print("Enter Roll Number: ");

rollNo = Integer.parseInt(br.readLine());

System.out.print("Enter Name: ");

name = br.readLine();

System.out.print("Enter Class: ");

className = br.readLine();

System.out.print("Enter Percentage: ");

per = Double.parseDouble(br.readLine());

// Method to display student details

public void display() {

System.out.println("\n--- Student Details ---");

System.out.println("Roll Number: " + rollNo);

System.out.println("Name: " + name);

System.out.println("Class: " + className);

System.out.println("Percentage: " + per);

// Main class

public class TestStudent {

public static void main(String[] args) throws IOException {

Student s = new Student();


s.accept();

s.display();

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.

[ [diagram your name ------- your class ---------- fy-- sy---]]

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class StudentInfoGUI extends JFrame implements ActionListener {

JTextField nameField, resultField;

JRadioButton fy, sy, ty;

JCheckBox music, dance, sports;

JButton submit;

ButtonGroup classGroup;

public StudentInfoGUI() {

setTitle("Student Information");

setSize(400, 350);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setLayout(new GridLayout(6, 1));

// Panel 1: Name

JPanel p1 = new JPanel(new FlowLayout());


p1.add(new JLabel("Your Name:"));

nameField = new JTextField(20);

p1.add(nameField);

// Panel 2: Class and Hobbies labels

JPanel p2 = new JPanel(new GridLayout(1, 2));

p2.add(new JLabel("Your Class", SwingConstants.CENTER));

p2.add(new JLabel("Your Hobbies", SwingConstants.CENTER));

// Panel 3: Class and Hobbies options

JPanel p3 = new JPanel(new GridLayout(3, 2));

// Radio Buttons for Class

fy = new JRadioButton("FY");

sy = new JRadioButton("SY");

ty = new JRadioButton("TY");

classGroup = new ButtonGroup();

classGroup.add(fy);

classGroup.add(sy);

classGroup.add(ty);

// Checkboxes for Hobbies

music = new JCheckBox("Music");

dance = new JCheckBox("Dance");

sports = new JCheckBox("Sports");


p3.add(fy); p3.add(music);

p3.add(sy); p3.add(dance);

p3.add(ty); p3.add(sports);

// Panel 4: Submit button

JPanel p4 = new JPanel();

submit = new JButton("Submit");

submit.addActionListener(this);

p4.add(submit);

// Panel 5: Result field

JPanel p5 = new JPanel();

resultField = new JTextField(30);

resultField.setEditable(false);

p5.add(resultField);

// Add panels to frame

add(p1);

add(p2);

add(p3);

add(p4);

add(p5);

setVisible(true);

public void actionPerformed(ActionEvent e) {


String name = nameField.getText();

String cls = "";

if (fy.isSelected()) cls = "FY";

else if (sy.isSelected()) cls = "SY";

else if (ty.isSelected()) cls = "TY";

String hobbies = "";

if (music.isSelected()) hobbies += "Music ";

if (dance.isSelected()) hobbies += "Dance ";

if (sports.isSelected()) hobbies += "Sports ";

resultField.setText("Name: " + name + " Class: " + cls + " Hobbies: " + hobbies);

public static void main(String[] args) {

new StudentInfoGUI();

Slip 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.

// Item class

class Item {

private int itemNumber;


private String itemName;

private double itemPrice;

// Static variable to keep count of objects

private static int count = 0;

// Default constructor

public Item() {

this.itemNumber = 0;

this.itemName = "Unknown";

this.itemPrice = 0.0;

count++;

// Parameterized constructor

public Item(int itemNumber, String itemName, double itemPrice) {

this.itemNumber = itemNumber;

this.itemName = itemName;

this.itemPrice = itemPrice;

count++;

// Static method to get object count

public static int getObjectCount() {

return count;

}
// Method to display item details

public void display() {

System.out.println("Item Number: " + itemNumber);

System.out.println("Item Name: " + itemName);

System.out.println("Item Price: " + itemPrice);

System.out.println("---------------------------");

// Main class

public class TestItem {

public static void main(String[] args) {

// Creating objects using parameterized constructor

Item i1 = new Item(101, "Laptop", 55000);

i1.display();

System.out.println("Total Items: " + Item.getObjectCount() + "\n");

Item i2 = new Item(102, "Mouse", 800);

i2.display();

System.out.println("Total Items: " + Item.getObjectCount() + "\n");

Item i3 = new Item(103, "Keyboard", 1500);

i3.display();

System.out.println("Total Items: " + Item.getObjectCount() + "\n");

}
Q2) Define a class ‘Donor’ to store the below mentioned details of a blood donor. name, age,
address, contactnumber, bloodgroup, date of last donation. Create ‘n’ objects of this class for all
the regular donors at Pune. Write these objects to a file. Read these objects from the file and
display only those donors’ details whose blood group is ‘A+ve’ and had not donated for the
recent six months.

import java.io.*;

import java.time.LocalDate;

import java.time.Period;

import java.time.format.DateTimeFormatter;

import java.util.*;

// Donor class implementing Serializable

class Donor implements Serializable {

private String name;

private int age;

private String address;

private String contactNumber;

private String bloodGroup;

private String lastDonationDate; // format: yyyy-MM-dd

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;

}
public String getBloodGroup() {

return bloodGroup;

public String getLastDonationDate() {

return lastDonationDate;

public void display() {

System.out.println("Name: " + name);

System.out.println("Age: " + age);

System.out.println("Address: " + address);

System.out.println("Contact Number: " + contactNumber);

System.out.println("Blood Group: " + bloodGroup);

System.out.println("Last Donation Date: " + lastDonationDate);

System.out.println("----------------------------");

// Main class

public class DonorManagement {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

List<Donor> donors = new ArrayList<>();

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");


// Input donor details

System.out.print("Enter number of donors: ");

int n = Integer.parseInt(sc.nextLine());

for (int i = 0; i < n; i++) {

System.out.println("\nEnter details of donor " + (i + 1) + ":");

System.out.print("Name: ");

String name = sc.nextLine();

System.out.print("Age: ");

int age = Integer.parseInt(sc.nextLine());

System.out.print("Address: ");

String address = sc.nextLine();

System.out.print("Contact Number: ");

String contact = sc.nextLine();

System.out.print("Blood Group: ");

String bg = sc.nextLine();

System.out.print("Date of Last Donation (yyyy-MM-dd): ");

String date = sc.nextLine();

donors.add(new Donor(name, age, address, contact, bg, date));

// Write objects to file

try (ObjectOutputStream oos = new ObjectOutputStream(new


FileOutputStream("donors.dat"))) {

for (Donor d : donors) {

oos.writeObject(d);
}

} catch (IOException e) {

System.out.println("Error writing to file: " + e);

// Read objects from file and filter donors

System.out.println("\n--- Eligible Donors (A+ve, not donated in last 6 months) ---");

try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("donors.dat"))) {

while (true) {

try {

Donor d = (Donor) ois.readObject();

if (d.getBloodGroup().equalsIgnoreCase("A+ve")) {

LocalDate lastDonation = LocalDate.parse(d.getLastDonationDate(), formatter);

LocalDate today = LocalDate.now();

Period p = Period.between(lastDonation, today);

if (p.getMonths() >= 6 || p.getYears() > 0) {

d.display();

} catch (EOFException eof) {

break; // End of file reached

} catch (IOException | ClassNotFoundException e) {

System.out.println("Error reading from file: " + e);

}}
Slip 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.

// Employee class

class Employee {

protected String name;

protected int id;

protected double basicSalary;

public Employee(String name, int id, double basicSalary) {

this.name = name;

this.id = id;

this.basicSalary = basicSalary;

// Method to get salary

public double getSalary() {

return basicSalary;

public void display() {

System.out.println("Employee ID: " + id);

System.out.println("Employee Name: " + name);

System.out.println("Salary: " + getSalary());


System.out.println("---------------------------");

// Manager class extending Employee

class Manager extends Employee {

private double ta; // Traveling Allowance

private double hra; // House Rent Allowance

public Manager(String name, int id, double basicSalary, double ta, double hra) {

super(name, id, basicSalary);

this.ta = ta;

this.hra = hra;

// Overriding getSalary method

@Override

public double getSalary() {

return basicSalary + ta + hra;

@Override

public void display() {

System.out.println("Manager ID: " + id);

System.out.println("Manager Name: " + name);

System.out.println("Salary (with TA & HRA): " + getSalary());

System.out.println("---------------------------");
}

// Main class

public class TestEmployee {

public static void main(String[] args) {

// Creating Employee object

Employee e1 = new Employee("Alice", 101, 50000);

e1.display();

// Creating Manager object

Manager m1 = new Manager("Bob", 201, 60000, 5000, 8000);

m1.display();

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 fromuser before deleting text files. Also, display a count
showing the number of files deleted,if any, from the directory.ii)If it is a file display various details
of that file.

import java.io.*;

import java.util.Scanner;

public class FileDirectoryOps {

public static void main(String[] args) {

if (args.length < 1) {

System.out.println("Please provide a file or directory path as a command-line argument.");

return;
}

File f = new File(args[0]);

Scanner sc = new Scanner(System.in);

if (!f.exists()) {

System.out.println("The specified path does not exist.");

return;

if (f.isDirectory()) {

System.out.println("It is a directory: " + f.getAbsolutePath());

File[] files = f.listFiles((dir, name) -> name.endsWith(".txt"));

if (files == null || files.length == 0) {

System.out.println("No text files (.txt) found in the directory.");

} else {

System.out.println("Text files found: " + files.length);

System.out.print("Do you want to delete all text files? (yes/no): ");

String choice = sc.nextLine();

if (choice.equalsIgnoreCase("yes")) {

int deletedCount = 0;

for (File file : files) {

if (file.delete()) {

deletedCount++;

}
}

System.out.println("Number of text files deleted: " + deletedCount);

} else {

System.out.println("Delete operation canceled.");

} else if (f.isFile()) {

System.out.println("It is a file: " + f.getAbsolutePath());

System.out.println("File Name: " + f.getName());

System.out.println("Path: " + f.getPath());

System.out.println("Absolute Path: " + f.getAbsolutePath());

System.out.println("Writable: " + f.canWrite());

System.out.println("Readable: " + f.canRead());

System.out.println("File Size (bytes): " + f.length());

System.out.println("Last Modified: " + f.lastModified());

} else {

System.out.println("Invalid path.");

Output:- //sample dicector

java FileDirectoryOps C:\Users\Pune\Documents\TestDir

It is a directory: C:\Users\Pune\Documents\TestDir

Text files found: 3

Do you want to delete all text files? (yes/no): yes

Number of text files deleted: 3

//sample run file  java FileDirectoryOps C:\Users\Pune\Documents\TestDir\file1.txt


It is a file: C:\Users\Pune\Documents\TestDir\file1.txt

File Name: file1.txt

Path: C:\Users\Pune\Documents\TestDir\file1.txt

Absolute Path: C:\Users\Pune\Documents\TestDir\file1.txt

Writable: true

Readable: true

File Size (bytes): 2048

Last Modified: 1696845600000

Slip 28

Q1) Write a program that reads on file name from the user, then displays information about
whether the file exists, whether the file is readable, whether the file is writable, the type of file and
the length of the file in bytes.

import java.io.*;

import java.util.Scanner;

public class FileInfo {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter the file name or path: ");

String fileName = sc.nextLine();

File file = new File(fileName);

if (!file.exists()) {

System.out.println("File does not exist.");

return;
}

System.out.println("File exists: " + file.exists());

System.out.println("Readable: " + file.canRead());

System.out.println("Writable: " + file.canWrite());

System.out.println("Is a file: " + file.isFile());

System.out.println("Is a directory: " + file.isDirectory());

System.out.println("File length (bytes): " + file.length());

System.out.println("Absolute path: " + file.getAbsolutePath());

Output:- // sample output// Enter the file name or path: C:\Users\Pune\Documents\file1.txt

File exists: true

Readable: true

Writable: true

Is a file: true

Is a directory: false

File length (bytes): 1024

Absolute path: C:\Users\Pune\Documents\file1.txt

Q2) Write a program called SwingTemperatureConverter to convert temperature values between


Celsius and Fahrenheit. User can enter either the Celsius or the Fahrenheit value,in floating-point
number. Hints: To display a floating-point number in a specific format (e.g., 1 decimal place),
use the static method String.format(), which has the same form as printf(). For example,
String.format("%.1f", 1.234) returns String "1.2"

[ table temperature converter ---------- Celsius ,, Fahrenheit,, ]

SwingTemperatureConverter.java

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

import java.awt.event.*;

public class SwingTemperatureConverter extends JFrame {

private JTextField celsiusField;

private JTextField fahrenheitField;

public SwingTemperatureConverter() {

// Set the title of the window

setTitle("Temperature Converter");

setSize(300, 150);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new GridLayout(2, 2, 10, 10));

// Create labels and text fields

JLabel celsiusLabel = new JLabel("Celsius:");

JLabel fahrenheitLabel = new JLabel("Fahrenheit:");

celsiusField = new JTextField();

fahrenheitField = new JTextField();

// Add components to frame

add(celsiusLabel);

add(celsiusField);

add(fahrenheitLabel);

add(fahrenheitField);
// Add listeners

celsiusField.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

convertCelsiusToFahrenheit();

});

fahrenheitField.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

convertFahrenheitToCelsius();

});

private void convertCelsiusToFahrenheit() {

try {

double celsius = Double.parseDouble(celsiusField.getText());

double fahrenheit = (celsius * 9 / 5) + 32;

fahrenheitField.setText(String.format("%.1f", fahrenheit));

} catch (NumberFormatException ex) {

JOptionPane.showMessageDialog(this, "Please enter a valid number for Celsius.");

private void convertFahrenheitToCelsius() {

try {

double fahrenheit = Double.parseDouble(fahrenheitField.getText());


double celsius = (fahrenheit - 32) * 5 / 9;

celsiusField.setText(String.format("%.1f", celsius));

} catch (NumberFormatException ex) {

JOptionPane.showMessageDialog(this, "Please enter a valid number for Fahrenheit.");

public static void main(String[] args) {

SwingTemperatureConverter frame = new SwingTemperatureConverter();

frame.setVisible(true);

Output:- Celsius = 37.5 Fahrenheit = 99.5

Fahrenheit = 32 Celsius = 0.0

Slip 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.Scanner;

// Customer class

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;

public String getContactNumber() {

return contactNumber;

public void display() {

System.out.println("Customer Number: " + custNo);

System.out.println("Customer Name: " + custName);

System.out.println("Contact Number: " + contactNumber);

System.out.println("Address: " + custAddr);

System.out.println("---------------------------");

// Main class

public class TestCustomer {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter number of customers: ");

int n = sc.nextInt();

sc.nextLine(); // consume newline

Customer[] customers = new Customer[n];

// Input customer details

for (int i = 0; i < n; i++) {

System.out.println("\nEnter details of customer " + (i + 1) + ":");

System.out.print("Customer Number: ");

int no = sc.nextInt();

sc.nextLine(); // consume newline

System.out.print("Customer Name: ");

String name = sc.nextLine();

System.out.print("Contact Number: ");

String contact = sc.nextLine();

System.out.print("Address: ");

String addr = sc.nextLine();

customers[i] = new Customer(no, name, contact, addr);

// Search by contact number

System.out.print("\nEnter contact number to search: ");

String searchContact = sc.nextLine();


boolean found = false;

for (Customer c : customers) {

if (c.getContactNumber().equals(searchContact)) {

System.out.println("\nCustomer found:");

c.display();

found = true;

break;

if (!found) {

System.out.println("Customer with contact number " + searchContact + " not found.");

Q2) Write a program to create a super class Vehicle having members Company and price.
Derive two different classes LightMotorVehicle(mileage) and HeavyMotorVehicle
(capacity_in_tons). Accept the information for "n" vehicles and display the information in
appropriate form. While taking data, ask user about the type of vehicle first.

import java.util.Scanner;

// Superclass Vehicle

class Vehicle {

protected String company;

protected double price;


public Vehicle(String company, double price) {

this.company = company;

this.price = price;

public void display() {

System.out.println("Company: " + company);

System.out.println("Price: " + price);

// Subclass LightMotorVehicle

class LightMotorVehicle extends Vehicle {

private double mileage;

public LightMotorVehicle(String company, double price, double mileage) {

super(company, price);

this.mileage = mileage;

@Override

public void display() {

System.out.println("\n--- Light Motor Vehicle ---");

super.display();

System.out.println("Mileage: " + mileage + " km/l");

}
// Subclass HeavyMotorVehicle

class HeavyMotorVehicle extends Vehicle {

private double capacityInTons;

public HeavyMotorVehicle(String company, double price, double capacityInTons) {

super(company, price);

this.capacityInTons = capacityInTons;

@Override

public void display() {

System.out.println("\n--- Heavy Motor Vehicle ---");

super.display();

System.out.println("Capacity: " + capacityInTons + " tons");

// Main class

public class TestVehicle {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter number of vehicles: ");

int n = sc.nextInt();

sc.nextLine(); // consume newline


Vehicle[] vehicles = new Vehicle[n];

for (int i = 0; i < n; i++) {

System.out.println("\nEnter type of vehicle (1 = Light, 2 = Heavy): ");

int type = sc.nextInt();

sc.nextLine(); // consume newline

System.out.print("Enter company name: ");

String company = sc.nextLine();

System.out.print("Enter price: ");

double price = sc.nextDouble();

if (type == 1) {

System.out.print("Enter mileage (km/l): ");

double mileage = sc.nextDouble();

vehicles[i] = new LightMotorVehicle(company, price, mileage);

} else if (type == 2) {

System.out.print("Enter capacity in tons: ");

double capacity = sc.nextDouble();

vehicles[i] = new HeavyMotorVehicle(company, price, capacity);

} else {

System.out.println("Invalid type! Skipping vehicle entry.");

i--; // repeat this iteration

sc.nextLine(); // consume newline

continue;

sc.nextLine(); // consume newline


}

// Display all vehicles

System.out.println("\n--- Vehicle Information ---");

for (Vehicle v : vehicles) {

v.display();

Output:- Enter number of vehicles: 2

Enter type of vehicle (1 = Light, 2 = Heavy):

Enter company name: Honda

Enter price: 800000

Enter mileage (km/l): 25

Enter type of vehicle (1 = Light, 2 = Heavy):

Enter company name: Tata

Enter price: 1500000

Enter capacity in tons: 10

--- Vehicle Information ---

--- Light Motor Vehicle ---

Company: Honda
Price: 800000.0

Mileage: 25.0 km/l

--- Heavy Motor Vehicle ---

Company: Tata

Price: 1500000.0

Capacity: 10.0 tons

Slip 30

Q1) Write program to define class Person with data member as Personname,Aadharno, Panno.
Accept information for 5 objects and display appropriate information (use this keyword).

import java.util.Scanner;

// Person class

class Person {

private String personName;

private String aadharNo;

private String panNo;

// Parameterized constructor using 'this' keyword

public Person(String personName, String aadharNo, String panNo) {

this.personName = personName;

this.aadharNo = aadharNo;

this.panNo = panNo;

}
// Method to display person details

public void display() {

System.out.println("Person Name: " + this.personName);

System.out.println("Aadhar No: " + this.aadharNo);

System.out.println("PAN No: " + this.panNo);

System.out.println("---------------------------");

// Main class

public class TestPerson {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

Person[] persons = new Person[5];

// Accepting information for 5 persons

for (int i = 0; i < 5; i++) {

System.out.println("\nEnter details for Person " + (i + 1) + ":");

System.out.print("Name: ");

String name = sc.nextLine();

System.out.print("Aadhar No: ");

String aadhar = sc.nextLine();

System.out.print("PAN No: ");

String pan = sc.nextLine();

persons[i] = new Person(name, aadhar, pan);

}
// Displaying all person details

System.out.println("\n--- Person Details ---");

for (Person p : persons) {

p.display();

Q2) Write a program that creates a user interface to perform integer divisions. The user enters
two numbers in the text fields, Number1 and Number2. The division of Number1 and Number2 is
displayed in the Result field when the Divide button is clicked. If Number1 or Number2 were not
an integer, the program would throw a NumberFormatException. If Number2 were Zero, the
program would throw an Arithmetic Exception Display the exception in a message dialog box

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class IntegerDivisionGUI extends JFrame implements ActionListener {

private JTextField num1Field, num2Field, resultField;

private JButton divideButton;

public IntegerDivisionGUI() {

setTitle("Integer Division");

setSize(400, 200);

setLayout(new GridLayout(4, 2, 10, 10));

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Labels

JLabel num1Label = new JLabel("Number1:");

JLabel num2Label = new JLabel("Number2:");

JLabel resultLabel = new JLabel("Result:");

// Text fields

num1Field = new JTextField();

num2Field = new JTextField();

resultField = new JTextField();

resultField.setEditable(false);

// Button

divideButton = new JButton("Divide");

divideButton.addActionListener(this);

// Add components to frame

add(num1Label);

add(num1Field);

add(num2Label);

add(num2Field);

add(resultLabel);

add(resultField);

add(new JLabel()); // empty placeholder

add(divideButton);

setVisible(true);

}
@Override

public void actionPerformed(ActionEvent e) {

try {

int num1 = Integer.parseInt(num1Field.getText());

int num2 = Integer.parseInt(num2Field.getText());

if (num2 == 0) {

throw new ArithmeticException("Cannot divide by zero!");

int result = num1 / num2;

resultField.setText(String.valueOf(result));

} catch (NumberFormatException nfe) {

JOptionPane.showMessageDialog(this,

"Please enter valid integers.",

"Number Format Exception",

JOptionPane.ERROR_MESSAGE);

} catch (ArithmeticException ae) {

JOptionPane.showMessageDialog(this,

ae.getMessage(),

"Arithmetic Exception",

JOptionPane.ERROR_MESSAGE);

}
public static void main(String[] args) {

new IntegerDivisionGUI();

You might also like