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

Java slips solution sem 5

The document contains Java solutions for various programming problems, including prime number detection, BMI calculation, sorting cities, handling patient data, matrix operations, and implementing inheritance. Each problem is accompanied by a code solution and explanations of the logic used. The solutions demonstrate key Java concepts such as classes, methods, arrays, exception handling, and GUI development using AWT.

Uploaded by

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

Java slips solution sem 5

The document contains Java solutions for various programming problems, including prime number detection, BMI calculation, sorting cities, handling patient data, matrix operations, and implementing inheritance. Each problem is accompanied by a code solution and explanations of the logic used. The solutions demonstrate key Java concepts such as classes, methods, arrays, exception handling, and GUI development using AWT.

Uploaded by

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

JAVA SOLUTIONS ALL 30 SLIPS :

SAVE FILE:-
Classname.java
Compiler:-
Javac filename.java
Execute (without extension):-
Java filename
Slip no-1

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

Ans:-
public class PrimeNumbersInArray {
public static void main(String[] args) {
int n = args.length;
for (int i = 0; i < n; i++) {
int num = Integer.parseInt(args[i]);
if (isPrime(num)) {
System.out.println(num + " is prime.");
} else {
System.out.println(num + " is not 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;
}
}

o/p = run : java PrimeNumbersInArray 2 3 4 5 6

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

Ans:-
abstract class Staff {
protected int id;
protected String name;
public Staff(int id, String name) {
this.id = id;
this.name = name;
}
}

class OfficeStaff extends Staff {


private String department;

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


super(id, name);
this.department = department;
}

public void display() {


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

public class OfficeStaffMain {


public static void main(String[] args) {
OfficeStaff[] staff = new OfficeStaff[3];
staff[0] = new OfficeStaff(1, "John", "HR");
staff[1] = new OfficeStaff(2, "Jane", "Finance");
staff[2] = new OfficeStaff(3, "Doe", "IT");

for (OfficeStaff os : staff) {


os.display();
}
}
}

Slip no-2
Q1) Write a program to read the First Name and Last Name of a person, his weight and height
using command line arguments. Calculate the BMI Index which is defined as the individual's
body mass divided by the square of their height.

(Hint: BMI = Wts. In kgs / (ht)²)

Ans:-

public class BMIIndex {

public static void main(String[] args) {

if (args.length < 4) {

System.out.println("Usage: FirstName LastName Weight Height");

return;

String firstName = args[0];

String lastName = args[1];

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

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

double bmi = weight / (height * height);

System.out.println(firstName + " " + lastName + "'s BMI: " + 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 static
method avg(). Define a static sort method which sorts the array on the basis of average. Display
the player details in sorted order.
Ans:-
import java.util.Arrays;

class CricketPlayer {
String name;
int no_of_innings, no_of_times_notout, total_runs;
double bat_avg;

public CricketPlayer(String name, int no_of_innings, int no_of_times_notout, int total_runs) {


this.name = name;
this.no_of_innings = no_of_innings;
this.no_of_times_notout = no_of_times_notout;
this.total_runs = total_runs;
this.bat_avg = 0;
}

public static double avg(CricketPlayer player) {


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

public static void sortPlayers(CricketPlayer[] players) {


Arrays.sort(players, (a, b) -> Double.compare(b.bat_avg, a.bat_avg));
}

public void display() {


System.out.println("Name: " + name + ", Batting Average: " + bat_avg);
}
}

public class CricketPlayerMain {


public static void main(String[] args) {
CricketPlayer[] players = new CricketPlayer[3];
players[0] = new CricketPlayer("Player1", 20, 5, 800);
players[1] = new CricketPlayer("Player2", 15, 3, 600);
players[2] = new CricketPlayer("Player3", 10, 2, 400);

for (CricketPlayer player : players) {


CricketPlayer.avg(player);
}

CricketPlayer.sortPlayers(players);

for (CricketPlayer player : players) {


player.display();
}
}
}

Slip no-3

Q1. Write a program to accept 'n' name of cities from the user and sort them in ascending order.
Ans:
import java.util.Arrays;
import java.util.Scanner;

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();

String[] cities = new String[n];


System.out.println("Enter the cities:");
for (int i = 0; i < n; i++) {
cities[i] = sc.nextLine();
}

Arrays.sort(cities);
System.out.println("Cities in ascending order:");
for (String city : cities) {
System.out.println(city);
}
}
}

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 than
95% and HRCT scan report greater than 10, then throw user defined Exception "Patient is
Covid Positive(+) and Need to Hospitalized" otherwise display its information.
Ans:-
class CovidPositiveException extends Exception {
public CovidPositiveException(String message) {
super(message);
}
}

class Patient {
String patient_name;
int patient_age;
double patient_oxy_level;
double patient_HRCT_report;

public Patient(String patient_name, int patient_age, double patient_oxy_level, double


patient_HRCT_report) {
this.patient_name = patient_name;
this.patient_age = patient_age;
this.patient_oxy_level = patient_oxy_level;
this.patient_HRCT_report = patient_HRCT_report;
}

public void checkCovidStatus() throws CovidPositiveException {


if (patient_oxy_level < 95 && patient_HRCT_report > 10) {
throw new CovidPositiveException("Patient is Covid Positive (+) and Needs to be
Hospitalized");
} else {
System.out.println("Patient is Healthy: " + patient_name);
}
}
}

public class PatientMain {


public static void main(String[] args) {
Patient patient = new Patient("John", 45, 92, 12);
try {
patient.checkCovidStatus();
} catch (CovidPositiveException e) {
System.out.println(e.getMessage());
}
}
}

Slip no-4

Q1) Write a program to print an array after changing the rows and columns of a given two-
dimensional array.
Ans:-
import java.util.Scanner;

public class ArrayTranspose {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows and columns:");
int rows = sc.nextInt();
int cols = sc.nextInt();
int[][] matrix = new int[rows][cols];

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


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = sc.nextInt();
}
}

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


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transpose[j][i] = matrix[i][j];
}
}

System.out.println("Transposed Matrix:");
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(transpose[i][j] + " ");
}
System.out.println();
}
}
}

Q2) Write a program to design a screen using Awt that will take a user name and password. It
the user name and Jpassword are not same, raise an Exception with appropriate message User
can have 3 login chances only. Use clear button to clear the TextFields.
Ans:
import java.awt.*;
import java.awt.event.*;

public class LoginScreenAWT extends Frame implements ActionListener {


TextField tfUsername, tfPassword;
Button loginButton, clearButton;
Label lblMessage;
int attempts = 3;

LoginScreenAWT() {
setTitle("Login Screen");
setSize(400, 300);
setLayout(new GridLayout(4, 2));

Label lblUsername = new Label("Username:");


Label lblPassword = new Label("Password:");

tfUsername = new TextField();


tfPassword = new TextField();
tfPassword.setEchoChar('*');

loginButton = new Button("Login");


clearButton = new Button("Clear");

lblMessage = new Label("");


add(lblUsername);
add(tfUsername);
add(lblPassword);
add(tfPassword);
add(loginButton);
add(clearButton);
add(lblMessage);

loginButton.addActionListener(this);
clearButton.addActionListener(this);

setVisible(true);
}

public void actionPerformed(ActionEvent e) {


if (e.getSource() == loginButton) {
String username = tfUsername.getText();
String password = tfPassword.getText();

if (attempts > 0) {
if (username.equals(password)) {
lblMessage.setText("Login successful!");
} else {
attempts--;
lblMessage.setText("Invalid Login. Attempts left: " + attempts);
if (attempts == 0) {
lblMessage.setText("Account locked.");
loginButton.setEnabled(false);
}
}
}
} else if (e.getSource() == clearButton) {
tfUsername.setText("");
tfPassword.setText("");
lblMessage.setText("");
}
}

public static void main(String[] args) {


new LoginScreenAWT();
}
}

Slip no-5

Q1) Write a program for multilevel inheritance such that Country is inherited from Continent
State is inherited from Country. Display the place, State, Country and Continent.
Ans:-
class Continent {
String continentName;

Continent(String cname) {
this.continentName = cname;
}
}

class Country extends Continent {


String countryName;

Country(String cname, String countryName) {


super(cname);
this.countryName = countryName;
}
}

class State extends Country {


String stateName;

State(String cname, String countryName, String stateName) {


super(cname, countryName);
this.stateName = stateName;
}

void displayDetails() {
System.out.println("Continent: " + continentName);
System.out.println("Country: " + countryName);
System.out.println("State: " + stateName);
}
}

public class MultiLevelInheritance {


public static void main(String[] args) {
State state = new State("Asia", "India", "Maharashtra");
state.displayDetails();
}
}

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

Multiplication

Exit

Ans:-

import java.util.Scanner;

public class MatrixOperations {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of rows and columns of matrices:");

int rows = sc.nextInt();

int cols = sc.nextInt();

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

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

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


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

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

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

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

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

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

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

int choice;

do {

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:

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

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

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

sum[i][j] = matrix1[i][j] + matrix2[i][j];

System.out.println("Sum of matrices:");

for (int[] row : sum) {

for (int element : row) {

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

System.out.println();

break;

case 2:

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

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

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

product[i][j] = 0;

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

product[i][j] += matrix1[i][k] * matrix2[k][j];


}

System.out.println("Product of matrices:");

for (int[] row : product) {

for (int element : row) {

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

System.out.println();

break;

case 3:

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

break;

default:

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

} while (choice != 3);

Slip no-6
Q1) Write a program to display the Employee(Empid, Empname, Empdesignation, Empsal)
information using toString().
Ans:-
class Employee {
int empId;
String empName, empDesignation;
double empSal;

Employee(int id, String name, String designation, double salary) {


this.empId = id;
this.empName = name;
this.empDesignation = designation;
this.empSal = salary;
}

@Override
public String toString() {
return "Employee ID: " + empId + "\nEmployee Name: " + empName +
"\nEmployee Designation: " + empDesignation + "\nEmployee Salary: " + empSal;
}

public static void main(String[] args) {


Employee emp = new Employee(101, "John Doe", "Software Engineer", 75000);
System.out.println(emp.toString());
}
}

Q2) Create an abstract class "order" having members id, description. Create two subclasses
"Purchase Order" and "Sales Order" having members customer name and Vendor name
respectively. Definemethods accept and display in all cases. Create 3 objects each of Purchas
Order and Sales Order and accept and display details.
Ans:
import java.util.Scanner;

abstract class Order {


int id;
String description;

abstract void accept();


abstract void display();
}
class PurchaseOrder extends Order {
String customerName;

@Override
void accept() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Order ID: ");
id = sc.nextInt();
sc.nextLine(); // Consume newline
System.out.print("Enter Order Description: ");
description = sc.nextLine();
System.out.print("Enter Customer Name: ");
customerName = sc.nextLine();
}

@Override
void display() {
System.out.println("Purchase Order ID: " + id + ", Description: " + description + ", Customer
Name: " + customerName);
}
}

class SalesOrder extends Order {


String vendorName;

@Override
void accept() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Order ID: ");
id = sc.nextInt();
sc.nextLine(); // Consume newline
System.out.print("Enter Order Description: ");
description = sc.nextLine();
System.out.print("Enter Vendor Name: ");
vendorName = sc.nextLine();
}

@Override
void display() {
System.out.println("Sales Order ID: " + id + ", Description: " + description + ", Vendor
Name: " + vendorName);
}
}

public class OrderManagement {


public static void main(String[] args) {
PurchaseOrder[] po = new PurchaseOrder[3];
SalesOrder[] so = new SalesOrder[3];

System.out.println("Enter Purchase Order Details:");


for (int i = 0; i < 3; i++) {
po[i] = new PurchaseOrder();
po[i].accept();
}

System.out.println("\nEnter Sales Order Details:");


for (int i = 0; i < 3; i++) {
so[i] = new SalesOrder();
so[i].accept();
}

System.out.println("\nPurchase Orders:");
for (PurchaseOrder order : po) {
order.display();
}

System.out.println("\nSales Orders:");
for (SalesOrder order : so) {
order.display();
}
}
}

Slip no-7

Q1) Design a class for Bank. Bank Class should support following operations;

a. Deposit a certain amount into an account

b. Withdraw a certain amount from an account

c. Return a Balance value specifying the amount with details


Ans:-
class Bank {
private double balance;

public Bank(double initialBalance) {


this.balance = initialBalance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: " + amount);
} else {
System.out.println("Deposit amount must be positive!");
}
}

public void withdraw(double amount) {


if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient balance or invalid amount!");
}
}

public void getBalance() {


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

public static void main(String[] args) {


Bank myAccount = new Bank(1000.0);
myAccount.deposit(500);
myAccount.withdraw(300);
myAccount.getBalance();
}
}

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.
Ans:-
import java.io.*;

public class FileReverse {


public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the file name: ");
String fileName = reader.readLine();

File file = new File(fileName);


if (!file.exists()) {
System.out.println("File does not exist.");
return;
}

BufferedReader fileReader = new BufferedReader(new FileReader(file));


StringBuilder content = new StringBuilder();

String line;
while ((line = fileReader.readLine()) != null) {
content.append(line).append("\n");
}

fileReader.close();

String reversedContent = new StringBuilder(content).reverse().toString();


String modifiedContent = changeCase(reversedContent);

System.out.println("Reversed and Case-Changed Content:");


System.out.println(modifiedContent);
} catch (IOException e) {
System.out.println("Error reading the file.");
}
}

public static String changeCase(String str) {


StringBuilder result = new StringBuilder();
for (char ch : str.toCharArray()) {
if (Character.isUpperCase(ch)) {
result.append(Character.toLowerCase(ch));
} else if (Character.isLowerCase(ch)) {
result.append(Character.toUpperCase(ch));
} else {
result.append(ch);
}
}
return result.toString();
}
}

Slip no-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))


Ans:-
class Sphere {
private double radius;

public Sphere(double radius) {


this.radius = radius;
}

public double calculateSurfaceArea() {


return 4 * Math.PI * radius * radius;
}

public double calculateVolume() {


return (4.0 / 3) * Math.PI * radius * radius * radius;
}

public static void main(String[] args) {


Sphere sphere = new Sphere(5.0);
System.out.println("Surface Area: " + sphere.calculateSurfaceArea());
System.out.println("Volume: " + sphere.calculateVolume());
}
}
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
Ans:-
import java.awt.*;
import java.awt.event.*;

public class MouseEventDemoAWT extends Frame implements MouseListener,


MouseMotionListener {
TextField tf;

MouseEventDemoAWT() {
tf = new TextField();
tf.setBounds(50, 50, 200, 30);
add(tf);

addMouseListener(this);
addMouseMotionListener(this);

setSize(400, 400);
setLayout(null);
setVisible(true);
}

public void mouseClicked(MouseEvent e) {


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

public void mouseMoved(MouseEvent e) {


tf.setText("Moved at: (" + e.getX() + ", " + e.getY() + ")");
}

// Other MouseListener methods


public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseDragged(MouseEvent e) {}

public static void main(String[] args) {


new MouseEventDemoAWT();
}
}

Slip no-9

Q1) Define a "Clock" class that does the following;

a. Accept Hours, Minutes and Seconds

b. Check the validity of numbers

c. Set the time to AM/PM mode

Use the necessary constructors and methods to do the above task


Ans:-

import java.util.Scanner;

class Clock {

private int hours;

private int minutes;

private int seconds;

public Clock(int hours, int minutes, int seconds) {

if (isValidTime(hours, minutes, seconds)) {

this.hours = hours;

this.minutes = minutes;

this.seconds = seconds;

} else {

throw new IllegalArgumentException("Invalid time provided.");

private boolean isValidTime(int hours, int minutes, int seconds) {

return (hours >= 0 && hours < 24) && (minutes >= 0 && minutes < 60) && (seconds >= 0
&& seconds < 60);

}
public void displayTime() {

String amPm = (hours < 12) ? "AM" : "PM";

int displayHours = (hours == 0) ? 12 : (hours > 12) ? hours - 12 : hours;

System.out.printf("Current Time: %02d:%02d:%02d %s%n", displayHours, minutes,


seconds, amPm);

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter hours (0-23): ");

int hours = sc.nextInt();

System.out.print("Enter minutes (0-59): ");

int minutes = sc.nextInt();

System.out.print("Enter seconds (0-59): ");

int seconds = sc.nextInt();

try {

Clock clock = new Clock(hours, minutes, seconds);

clock.displayTime();

} catch (IllegalArgumentException e) {

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

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
objects of class product and display the contents of each object and Also display the object
count.
Ans:
interface Marker {}

class Product implements Marker {


private int productId;
private String productName;
private double productCost;
private int productQuantity;
private static int objectCount = 0;

public Product() {
objectCount++;
}

public Product(int productId, String productName, double productCost, int productQuantity) {


this.productId = productId;
this.productName = productName;
this.productCost = productCost;
this.productQuantity = productQuantity;
objectCount++;
}

public void displayProductDetails() {


System.out.println("Product ID: " + productId +
", Name: " + productName +
", Cost: " + productCost +
", Quantity: " + productQuantity);
}

public static int getObjectCount() {


return objectCount;
}

public static void main(String[] args) {


Product p1 = new Product(101, "Laptop", 80000.00, 5);
Product p2 = new Product(102, "Smartphone", 30000.00, 10);
Product p3 = new Product(103, "Tablet", 20000.00, 15);

p1.displayProductDetails();
p2.displayProductDetails();
p3.displayProductDetails();

System.out.println("Total Products Created: " + Product.getObjectCount());


}
}

Slip no-10

Q1) Write a program to find the cube of given number using functional interface.
Ans:
import java.util.Scanner;

//FunctionalInterface
interface Cube {
double calculate(double number);
}

public class CubeCalculator {


public static void main(String[] args) {
Cube cube = (number) -> number * number * number;

Scanner sc = new Scanner(System.in);


System.out.print("Enter a number: ");
double number = sc.nextDouble();
double result = cube.calculate(number);

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


}
}

Q2) Write a program to create a package name student. Define class StudentInfo with method
to display information about student such as follno, class, and percentage. Create another class
StudentPer with method to find percentage of the student. Accept student details like rollno,
name, class and marks of 6 subject from user
Ans:
// In the package student
package student;

import java.util.Scanner;

class StudentInfo {
String rollNo;
String name;
String studentClass;
double[] marks = new double[6];

public void acceptDetails() {


Scanner sc = new Scanner(System.in);
System.out.print("Enter Roll Number: ");
rollNo = sc.nextLine();
System.out.print("Enter Name: ");
name = sc.nextLine();
System.out.print("Enter Class: ");
studentClass = sc.nextLine();
System.out.println("Enter Marks for 6 Subjects:");
for (int i = 0; i < 6; i++) {
System.out.print("Marks for Subject " + (i + 1) + ": ");
marks[i] = sc.nextDouble();
}
}

public void displayInfo() {


System.out.println("Roll Number: " + rollNo + ", Name: " + name +
", Class: " + studentClass);
}
}

class StudentPer {
public double calculatePercentage(double[] marks) {
double total = 0;
for (double mark : marks) {
total += mark;
}
return (total / (marks.length * 100)) * 100; // assuming each subject is out of 100
}
}

public class StudentManagement {


public static void main(String[] args) {
StudentInfo student = new StudentInfo();
student.acceptDetails();
student.displayInfo();

StudentPer studentPer = new StudentPer();


double percentage = studentPer.calculatePercentage(student.marks);
System.out.printf("Percentage: %.2f%%%n", percentage);
}
}

Slip no-11

Q1) Define an interface "Operation" which has method volume().Define a constant PI having a
value 3.142 Create a class cylinder which implements this interface (members - radius, height).
Create one object and calculate the volume.
Ans:
interface Operation {
double volume();
}

class Cylinder implements Operation {


private double radius;
private double height;
private static final double PI = 3.142;

public Cylinder(double radius, double height) {


this.radius = radius;
this.height = height;
}

//Override
public double volume() {
return PI * radius * radius * height;
}
public static void main(String[] args) {
Cylinder cylinder = new Cylinder(5, 10);
System.out.printf("Volume of Cylinder: %.2f%n", cylinder.volume());
}
}

Q2) Write a program to accept the username and password from user if username and
password are not same then raise "Invalid Password" with appropriate msg.
Ans:-
import java.util.Scanner;

public class UserAuthentication {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Username: ");
String username = sc.nextLine();
System.out.print("Enter Password: ");
String password = sc.nextLine();

if (!username.equals(password)) {
throw new IllegalArgumentException("Invalid Password!");
} else {
System.out.println("Login Successful!");
}
}
}

Slip no-12

Q1) Write a program to create parent class College(cno, cname, caddr) and derived class
Department(dno, dname) from College. Write a necessary methods to display College details.

Ans:

class College {

protected int cno;

protected String cname;


protected String caddr;

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

this.cno = cno;

this.cname = cname;

this.caddr = caddr;

public void displayCollegeDetails() {

System.out.println("College No: " + cno + ", Name: " + cname + ", Address: " + caddr);

class Department extends College {

private int dno;

private String dname;

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

super(cno, cname, caddr);

this.dno = dno;

this.dname = dname;
}

public void displayDepartmentDetails() {

displayCollegeDetails();

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

public static void main(String[] args) {

Department dept = new Department(1, "ABC College", "123 Main St", 101, "Computer
Science");

dept.displayDepartmentDetails();

Q2) Write a java program that works as a simple calculator. Use a grid layout to arrange buttons for the digits

and for the +, -, *, % operations. Add a text field to display the result.

Ans:-

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

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

private JTextField textField;

private String operator;

private double num1, num2, result;

public SimpleCalculator() {

setTitle("Simple Calculator");

setSize(300, 400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new GridLayout(4, 4));

textField = new JTextField();

textField.setEditable(false);

add(textField);

// Add buttons for digits

for (int i = 1; i <= 9; i++) {

addButton(String.valueOf(i));

addButton("0");

addButton("+");

addButton("-");

addButton("*");
addButton("/");

addButton("=");

addButton("C");

setVisible(true);

private void addButton(String text) {

JButton button = new JButton(text);

button.addActionListener(this);

add(button);

@Override

public void actionPerformed(ActionEvent e) {

String command = e.getActionCommand();

if (command.charAt(0) >= '0' && command.charAt(0) <= '9') {

textField.setText(textField.getText() + command);

} else if (command.equals("C")) {

textField.setText("");

operator = "";

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

num2 = Double.parseDouble(textField.getText());
switch (operator) {

case "+":

result = num1 + num2;

break;

case "-":

result = num1 - num2;

break;

case "*":

result = num1 * num2;

break;

case "/":

result = num1 / num2;

break;

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

} else {

operator = command;

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

textField.setText("");

public static void main(String[] args) {

new SimpleCalculator();
}

Slip no-13

Q1) Write a program to accept a file name from command prompt, if the file exits then display
number of words and lines in that file.
Ans:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileWordLineCounter {


public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java FileWordLineCounter <filename>");
return;
}

String filename = args[0];


try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line;
int lineCount = 0;
int wordCount = 0;

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


lineCount++;
String[] words = line.split("\\s+");
wordCount += words.length;
}

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


System.out.println("Number of words: " + wordCount);
} catch (IOException e) {
System.out.println("File not found or an error occurred: " + e.getMessage());
}
}
}
Q2) Write a program to display the system date and time in various formats shown below:

Current date is: 31/08/2021

Current date is : 08-31-2021

Current date is: Tuesday August 31 2021

Current date and time is: Fri August 31 15:25:59 IST 2021
Current date and time is: 31/08/21 15:25:59 PM +0530
Ans:-
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class DateTimeFormats {


public static void main(String[] args) {
Date now = new Date();

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


SimpleDateFormat format2 = new SimpleDateFormat("MM-dd-yyyy");
SimpleDateFormat format3 = new SimpleDateFormat("EEEE MMMM dd yyyy");
SimpleDateFormat format4 = new SimpleDateFormat("EEE MMMM dd HH:mm:ss z yyyy");
SimpleDateFormat format5 = new SimpleDateFormat("dd/MM/yy HH:mm:ss a");
format5.setTimeZone(TimeZone.getTimeZone("GMT+5:30"));

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


System.out.println("Current date is: " + format2.format(now));
System.out.println("Current date is: " + format3.format(now));
System.out.println("Current date and time is: " + format4.format(now));
System.out.println("Current date and time is: " + format5.format(now));
}
}

Slip no-14

Q1) Write a program to accept a number from the user, if number is zero then throw user
defined exception "Number is 0" otherwise check whether no is prime or not (Use static
keyword).
Ans:-
import java.util.Scanner;

class ZeroException extends Exception {


public ZeroException(String message) {
super(message);
}
}

public class PrimeChecker {


public static void checkNumber(int number) throws ZeroException {
if (number == 0) {
throw new ZeroException("Number is 0");
}
}

public static boolean isPrime(int number) {


if (number <= 1) return false;
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % 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 number = sc.nextInt();

try {
checkNumber(number);
if (isPrime(number)) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
} catch (ZeroException e) {
System.out.println(e.getMessage());
}
}
}

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

// File: SY/SYMarks.java

(1. Create the SYMarks class in the SY package.)

package SY;

public class SYMarks {

private int computerTotal;

private int mathsTotal;

private int electronicsTotal;

public SYMarks(int computerTotal, int mathsTotal, int electronicsTotal) {

this.computerTotal = computerTotal;

this.mathsTotal = mathsTotal;

this.electronicsTotal = electronicsTotal;

public int getComputerTotal() {

return computerTotal;
}

(2. Create the TYMarks class in the TY package.)

// File: TY/TYMarks.java

package TY;

public class TYMarks {

private int theory;

private int practicals;

public TYMarks(int theory, int practicals) {

this.theory = theory;

this.practicals = practicals;

public int getTotal() {

return theory + practicals;

(3. Create the Student class to manage student details and calculate grades.)

// File: Student.java

import SY.SYMarks;
import TY.TYMarks;

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;

class Student {

private int rollNumber;

private String name;

private SYMarks syMarks;

private TYMarks tyMarks;

public Student(int rollNumber, String name, SYMarks syMarks, TYMarks tyMarks) {

this.rollNumber = rollNumber;

this.name = name;

this.syMarks = syMarks;

this.tyMarks = tyMarks;

public String calculateGrade() {

int totalMarks = syMarks.getComputerTotal() + tyMarks.getTotal();

if (totalMarks >= 70) {


return "A";

} else if (totalMarks >= 60) {

return "B";

} else if (totalMarks >= 50) {

return "C";

} else if (totalMarks >= 40) {

return "Pass Class";

} else {

return "FAIL";

@Override

public String toString() {

return "Student Roll Number: " + rollNumber + ", Name: " + name + ", Grade: " +
calculateGrade();

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

List<Student> students = new ArrayList<>();


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

int n = scanner.nextInt();

scanner.nextLine(); // Consume newline

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

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

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

int rollNumber = scanner.nextInt();

scanner.nextLine(); // Consume newline

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

String name = scanner.nextLine();

System.out.print("SY Computer Total Marks: ");

int syComputerTotal = scanner.nextInt();

System.out.print("SY Maths Total Marks: ");

int syMathsTotal = scanner.nextInt();

System.out.print("SY Electronics Total Marks: ");

int syElectronicsTotal = scanner.nextInt();

SYMarks syMarks = new SYMarks(syComputerTotal, syMathsTotal, syElectronicsTotal);

System.out.print("TY Theory Marks: ");

int tyTheory = scanner.nextInt();


System.out.print("TY Practical Marks: ");

int tyPracticals = scanner.nextInt();

TYMarks tyMarks = new TYMarks(tyTheory, tyPracticals);

students.add(new Student(rollNumber, name, syMarks, tyMarks));

scanner.nextLine(); // Consume newline

System.out.println("\nStudent Results:");

for (Student student : students) {

System.out.println(student);

scanner.close();

Slip no-15

Q1) Accept the names of two files and copy the contents of the first to the second. First file
having Book name and Author name in file.
Ans:-
import java.io.*;

public class FileCopy {


public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the name of the source file: ");
String sourceFileName = null;
String destinationFileName = null;

try {
sourceFileName = reader.readLine();
System.out.print("Enter the name of the destination file: ");
destinationFileName = reader.readLine();
} catch (IOException e) {
System.out.println("Error reading input.");
return;
}

try (BufferedReader fileReader = new BufferedReader(new FileReader(sourceFileName));


BufferedWriter fileWriter = new BufferedWriter(new FileWriter(destinationFileName))) {

String line;
while ((line = fileReader.readLine()) != null) {
fileWriter.write(line);
fileWriter.newLine();
}

System.out.println("Contents copied from " + sourceFileName + " to " +


destinationFileName);
} catch (IOException e) {
System.out.println("Error processing files: " + e.getMessage());
}
}
}

Q2) Write a program to define a class Account having members custname, accno. Define
default and parameterized constructor. Create a subclass called SavingAccount with member
savingbal, minbal. Create a derived class AccountDetail that extends the class SavingAccount
with members, depositamt and withdrawalamt. Write a appropriate method to display customer
details.
Ans:-
class Account {
String custName;
String accNo;

// Default constructor
public Account() {
this.custName = "Unknown";
this.accNo = "0000";
}

// Parameterized constructor
public Account(String custName, String accNo) {
this.custName = custName;
this.accNo = accNo;
}
}

class SavingAccount extends Account {


double savingBal;
double minBal;

public SavingAccount(String custName, String accNo, double savingBal, double minBal) {


super(custName, accNo);
this.savingBal = savingBal;
this.minBal = minBal;
}
}

class AccountDetail extends SavingAccount {


double depositAmt;
double withdrawalAmt;

public AccountDetail(String custName, String accNo, double savingBal, double minBal,


double depositAmt, double withdrawalAmt) {
super(custName, accNo, savingBal, minBal);
this.depositAmt = depositAmt;
this.withdrawalAmt = withdrawalAmt;
}

public void displayCustomerDetails() {


System.out.println("Customer Name: " + custName);
System.out.println("Account Number: " + accNo);
System.out.println("Savings Balance: " + savingBal);
System.out.println("Minimum Balance: " + minBal);
System.out.println("Deposit Amount: " + depositAmt);
System.out.println("Withdrawal Amount: " + withdrawalAmt);
}
}

public class Main {


public static void main(String[] args) {
AccountDetail accountDetail = new AccountDetail("John Doe", "12345", 5000.00, 1000.00,
1500.00, 200.00);
accountDetail.displayCustomerDetails();
}
}

Slip no-16

Q1) Write a program to find the Square of given number using function interface.
Ans:-
import java.util.Scanner;

@FunctionalInterface
interface Square {
int calculate(int number);
}

public class SquareCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Create a lambda expression to implement the square calculation


Square squareFunction = (number) -> number * number;

System.out.print("Enter a number to find its square: ");


int number = scanner.nextInt();

int result = squareFunction.calculate(number);


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

scanner.close();
}
}

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

Ans:-
import java.awt.*;
import java.awt.event.*;

public class SquareAWT extends Frame implements ActionListener {


private TextField inputField;
private Label resultLabel;

public SquareAWT() {
// Set up the frame
setTitle("Square Calculator");
setSize(300, 200);
setLayout(new FlowLayout());

// Create UI components
Label promptLabel = new Label("Enter a number:");
inputField = new TextField(10);
Button calculateButton = new Button("Calculate Square");
resultLabel = new Label("");
// Add components to the frame
add(promptLabel);
add(inputField);
add(calculateButton);
add(resultLabel);

// Add action listener


calculateButton.addActionListener(this);

// Set frame visibility


setVisible(true);

// Close operation
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

@Override
public void actionPerformed(ActionEvent e) {
try {
int number = Integer.parseInt(inputField.getText());
int square = number * number;
resultLabel.setText("Square: " + square);
} catch (NumberFormatException ex) {
resultLabel.setText("Please enter a valid number.");
}
}

public static void main(String[] args) {


new SquareAWT();
}
}
Slip no-17
Q1) Design a Super class Customer (name, phone-number). Derive a class Depositor(accno,
balance) from Customer. Again, derive a class Borrower (loan-no, loan-amt) from Depositor.
Write necessary member functions to read and display the details of 'n'customers.
Ans:
import java.util.Scanner;

class Customer {
String name;
String phoneNumber;

public Customer(String name, String phoneNumber) {


this.name = name;
this.phoneNumber = phoneNumber;
}

public void display() {


System.out.println("Customer Name: " + name);
System.out.println("Phone Number: " + phoneNumber);
}
}

class Depositor extends Customer {


String accNo;
double balance;

public Depositor(String name, String phoneNumber, String accNo, double balance) {


super(name, phoneNumber);
this.accNo = accNo;
this.balance = balance;
}

@Override
public void display() {
super.display();
System.out.println("Account Number: " + accNo);
System.out.println("Balance: " + balance);
}
}

class Borrower extends Depositor {


String loanNo;
double loanAmt;

public Borrower(String name, String phoneNumber, String accNo, double balance, String
loanNo, double loanAmt) {
super(name, phoneNumber, accNo, balance);
this.loanNo = loanNo;
this.loanAmt = loanAmt;
}

@Override
public void display() {
super.display();
System.out.println("Loan Number: " + loanNo);
System.out.println("Loan Amount: " + loanAmt);
}
}

public class CustomerDetails {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of customers: ");
int n = scanner.nextInt();
scanner.nextLine(); // Consume newline

Borrower[] customers = new Borrower[n];

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


System.out.println("Enter details for customer " + (i + 1) + ":");
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("Phone Number: ");
String phoneNumber = scanner.nextLine();
System.out.print("Account Number: ");
String accNo = scanner.nextLine();
System.out.print("Balance: ");
double balance = scanner.nextDouble();
scanner.nextLine(); // Consume newline
System.out.print("Loan Number: ");
String loanNo = scanner.nextLine();
System.out.print("Loan Amount: ");
double loanAmt = scanner.nextDouble();
scanner.nextLine(); // Consume newline

customers[i] = new Borrower(name, phoneNumber, accNo, balance, loanNo, loanAmt);


}

System.out.println("\nCustomer Details:");
for (Borrower customer : customers) {
customer.display();
System.out.println();
}

scanner.close();
}
}

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
Ans:-
import javax.swing.*;
import java.awt.event.*;

public class StringManipulator extends JFrame implements ActionListener {


private JTextField textField1;
private JTextField textField2;
private JTextField resultField;
private JButton concatButton;
private JButton reverseButton;

public StringManipulator() {
// Create UI components
textField1 = new JTextField(15);
textField2 = new JTextField(15);
resultField = new JTextField(15);
resultField.setEditable(false);
concatButton = new JButton("Concatenate");
reverseButton = new JButton("Reverse");
// Set up the frame
setLayout(new FlowLayout());
add(new JLabel("String 1:"));
add(textField1);
add(new JLabel("String 2:"));
add(textField2);
add(concatButton);
add(reverseButton);
add(new JLabel("Result:"));
add(resultField);

// Add action listeners


concatButton.addActionListener(this);
reverseButton.addActionListener(this);

// Frame settings
setTitle("String Manipulator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == concatButton) {
String str1 = textField1.getText();
String str2 = textField2.getText();
resultField.setText(str1 + str2);
} else if (e.getSource() == reverseButton) {
String str1 = textField1.getText();
String reversed = new StringBuilder(str1).reverse().toString();
resultField.setText(reversed);
}
}

public static void main(String[] args) {


new StringManipulator();
}
}

Slip no18

Q1) Write a program to implement Border Layout Manager.

Ans:-

import java.awt.*;

import javax.swing.*;

public class BorderLayoutDemo {

public static void main(String[] args) {

JFrame frame = new JFrame("Border Layout Example");

frame.setSize(400, 200);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(new BorderLayout());

frame.add(new JButton("North"), BorderLayout.NORTH);

frame.add(new JButton("South"), BorderLayout.SOUTH);

frame.add(new JButton("East"), BorderLayout.EAST);

frame.add(new JButton("West"), BorderLayout.WEST);

frame.add(new JButton("Center"), BorderLayout.CENTER);

frame.setVisible(true);

}
}

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.
Ans:
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

class CricketPlayer {
String name;
int noOfInnings;
int noOfTimesNotOut;
int totalRuns;
double batAvg;

public CricketPlayer(String name, int noOfInnings, int noOfTimesNotOut, int totalRuns) {


this.name = name;
this.noOfInnings = noOfInnings;
this.noOfTimesNotOut = noOfTimesNotOut;
this.totalRuns = totalRuns;
this.batAvg = calculateAvg();
}

public double calculateAvg() {


if (noOfInnings - noOfTimesNotOut > 0) {
return (double) totalRuns / (noOfInnings - noOfTimesNotOut);
} else {
return 0.0; // Avoid division by zero
}
}

@Override
public String toString() {
return "Name: " + name + ", Innings: " + noOfInnings + ", Not Out: " + noOfTimesNotOut +
", Total Runs: " + totalRuns + ", Batting Average: " + batAvg;
}
}
public class CricketPlayerDetails {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of players: ");
int n = scanner.nextInt();
scanner.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 = scanner.nextLine();
System.out.print("No. of Innings: ");
int innings = scanner.nextInt();
System.out.print("No. of Times Not Out: ");
int notOut = scanner.nextInt();
System.out.print("Total Runs: ");
int runs = scanner.nextInt();
scanner.nextLine(); // Consume newline

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


}

// Sort players based on batting average


Arrays.sort(players, Comparator.comparingDouble(player -> player.batAvg));

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


for (CricketPlayer player : players) {
System.out.println(player);
}

scanner.close();
}
}

Slip no-19

Q1) Write a program to accept the two dimensional array from user and display sum of its
diagonal elements.
Ans:-

import java.util.Scanner;

public class DiagonalSum {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of rows and columns of the matrix (n x n): ");

int n = scanner.nextInt();

int[][] matrix = new int[n][n];

// Accepting the matrix from the user

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

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

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

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

int diagonalSum = 0;
// Calculating the sum of diagonal elements

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

diagonalSum += matrix[i][i]; // Main diagonal

diagonalSum += matrix[i][n - 1 - i]; // Secondary diagonal

// Subtract the middle element if n is odd, as it is counted twice

if (n % 2 != 0) {

diagonalSum -= matrix[n / 2][n / 2];

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

scanner.close();

Q2) Write a program which shows the combo box which includes list of T.Y.B.Sc.(Comp. Sci)
subjects. Display the selected subject in a text field.
Ans:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SubjectSelector extends JFrame {


private JTextField selectedSubjectField;

public SubjectSelector() {
setTitle("Subject Selector");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

String[] subjects = {
"Data Structures",
"Operating Systems",
"Database Management Systems",
"Software Engineering",
"Computer Networks"
};

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


selectedSubjectField = new JTextField(20);
selectedSubjectField.setEditable(false);

subjectComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selectedSubject = (String) subjectComboBox.getSelectedItem();
selectedSubjectField.setText(selectedSubject);
}
});

add(new JLabel("Select a Subject:"));


add(subjectComboBox);
add(new JLabel("Selected Subject:"));
add(selectedSubjectField);
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
SubjectSelector frame = new SubjectSelector();
frame.setVisible(true);
});
}
}

Slip no-20
Q1) Write a Program to illustrate multilevel Inheritance such that country is inherited from
continent. State is inherited from country. Display the place, state, country and continent.
Ans:
class Continent {
String continentName;

public Continent(String continentName) {


this.continentName = continentName;
}
}

class Country extends Continent {


String countryName;

public Country(String continentName, String countryName) {


super(continentName);
this.countryName = countryName;
}
}

class State extends Country {


String stateName;

public State(String continentName, String countryName, String stateName) {


super(continentName, countryName);
this.stateName = stateName;
}

public void displayDetails() {


System.out.println("Continent: " + continentName);
System.out.println("Country: " + countryName);
System.out.println("State: " + stateName);
}
}

public class InheritanceDemo {


public static void main(String[] args) {
State state = new State("Asia", "India", "Maharashtra");
state.displayDetails();
}
}

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:-
(1.Addition.java)
package Operation;

public class Addition {


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

public float subtract(float a, float b) {


return a - b;
}
}

(2.Maximum.java)
package Operation;

public class Maximum {


public int max(int a, int b) {
return Math.max(a, b);
}
}

(Main Class to Test the Package)


import Operation.Addition;
import Operation.Maximum;

public class OperationTest {


public static void main(String[] args) {
Addition addition = new Addition();
Maximum maximum = new Maximum();

// Testing Addition
int sum = addition.add(5, 10);
float difference = addition.subtract(5.5f, 3.5f);

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


System.out.println("Difference: " + difference);

// Testing Maximum
int max = maximum.max(10, 20);
System.out.println("Maximum: " + max);
}
}

Slip no-21

Q1) Define a class MyDate(Day, Month, year) with methods to accept and display a
MyDateobject. Accept date as dd,mm,yyyy. Throw user defined exception
"InvalidDateException" if the date is invalid.
Ans:
class InvalidDateException extends Exception {
public InvalidDateException(String message) {
super(message);
}
}

class MyDate {
private int day;
private int month;
private int year;

public void acceptDate(int day, int month, int year) throws InvalidDateException {
if (month < 1 || month > 12) {
throw new InvalidDateException("Invalid month: " + month);
}
if (day < 1 || day > daysInMonth(month, year)) {
throw new InvalidDateException("Invalid day: " + day);
}
this.day = day;
this.month = month;
this.year = year;
}

private int daysInMonth(int month, int year) {


switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
return 31;
case 4: case 6: case 9: case 11:
return 30;
case 2:
return (isLeapYear(year)) ? 29 : 28;
default:
return 0;
}
}

private boolean isLeapYear(int year) {


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

public void displayDate() {


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

public class DateTest {


public static void main(String[] args) {
MyDate date = new MyDate();
try {
date.acceptDate(29, 2, 2020); // Valid date
date.displayDate();
date.acceptDate(31, 4, 2021); // Invalid date
} 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.
Ans:
class Employee {
private int id;
private String name;
private String deptName;
private double salary;
private static int objectCount = 0;

public Employee() {
objectCount++;
}

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


this(); // Calls default constructor to increment count
this.id = id;
this.name = name;
this.deptName = deptName;
this.salary = salary;
}

public static int getObjectCount() {


return objectCount;
}

public void displayDetails() {


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

public class EmployeeTest {


public static void main(String[] args) {
Employee emp1 = new Employee(1, "Alice", "HR", 50000);
emp1.displayDetails();
System.out.println("Total Employees: " + Employee.getObjectCount());

Employee emp2 = new Employee(2, "Bob", "IT", 60000);


emp2.displayDetails();
System.out.println("Total Employees: " + Employee.getObjectCount());
}
}

Slip no-22

Q1) Write a program to create an abstract class named Shape that contains two integers and
an empty method named printArea(). Provide three classes named Rectangle, Triangle and
Circle such that each one of the classes extends the class Shape. Each one of the classes
contain only the method printArea() that prints the area of the given shape. (use method
overriding).
Ans:-
abstract class Shape {
protected int dimension1;
protected int dimension2;

public abstract void printArea();


}

class Rectangle extends Shape {


public Rectangle(int length, int width) {
this.dimension1 = length;
this.dimension2 = width;
}

@Override
public void printArea() {
System.out.println("Area of Rectangle: " + (dimension1 * dimension2));
}
}

class Triangle extends Shape {


public Triangle(int base, int height) {
this.dimension1 = base;
this.dimension2 = height;
}

@Override
public void printArea() {
System.out.println("Area of Triangle: " + (0.5 * dimension1 * dimension2));
}
}

class Circle extends Shape {


public Circle(int radius) {
this.dimension1 = radius;
}

@Override
public void printArea() {
System.out.println("Area of Circle: " + (Math.PI * dimension1 * dimension1));
}
}
public class ShapeTest {
public static void main(String[] args) {
Shape rect = new Rectangle(5, 10);
Shape tri = new Triangle(4, 6);
Shape circ = new Circle(3);

rect.printArea();
tri.printArea();
circ.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).
Ans:-
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MouseEventDemo extends JFrame {


private JLabel label;

public MouseEventDemo() {
setTitle("Mouse Event Demo");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

// Create a label to display mouse events


label = new JLabel("Mouse Events", SwingConstants.CENTER);
label.setFont(new Font("Arial", Font.BOLD, 24));
label.setForeground(Color.RED); // Set text color to red
add(label, BorderLayout.CENTER);

// Add mouse listener using MouseAdapter


addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
label.setText("Mouse Clicked");
}

@Override
public void mouseEntered(MouseEvent e) {
label.setText("Mouse Entered");
}

@Override
public void mouseExited(MouseEvent e) {
label.setText("Mouse Exited");
}

@Override
public void mousePressed(MouseEvent e) {
label.setText("Mouse Pressed");
}

@Override
public void mouseReleased(MouseEvent e) {
label.setText("Mouse Released");
}
});
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
MouseEventDemo frame = new MouseEventDemo();
frame.setVisible(true);
});
}
}
Slip no-23

Q1) Define a class MyNumber having one private int data member. Write a default constructor
to initialize it to 0 and another constructor to initialize it to a value (Use this). Write methods
isNegative, is Positive, isZero, isOdd, isEven. Create an object in main. Use command line
arguments to pass a value to the Object.

Ans:
class MyNumber {
private int data;

// Default constructor
public MyNumber() {
this.data = 0; // Initialize to 0
}

// Parameterized constructor
public MyNumber(int value) {
this.data = value; // Initialize to the given value
}

public boolean isNegative() {


return data < 0;
}

public boolean isPositive() {


return data > 0;
}

public boolean isZero() {


return data == 0;
}

public boolean isOdd() {


return data % 2 != 0;
}

public boolean isEven() {


return data % 2 == 0;
}

public void displayProperties() {


System.out.println("Value: " + data);
System.out.println("Is Negative: " + isNegative());
System.out.println("Is Positive: " + isPositive());
System.out.println("Is Zero: " + isZero());
System.out.println("Is Odd: " + isOdd());
System.out.println("Is Even: " + isEven());
}
}

public class MyNumberTest {


public static void main(String[] args) {
int value = 0;

// Check if a command-line argument was provided


if (args.length > 0) {
try {
value = Integer.parseInt(args[0]); // Parse the command line argument
} catch (NumberFormatException e) {
System.out.println("Invalid input. Defaulting to 0.");
}
}

MyNumber myNumber = new MyNumber(value); // Create object with the provided value
myNumber.displayProperties(); // Display properties of the number
}
}
Q2) Write a simple currency converter, as shown in the figure. User can enter the amount of
"Singapore Dollars", "US Dollars", or "Euros", in floating-point number. The converted values
shall be displayed to 2 decimal places. Assume that 1 USD = 1.41 SGD, 1 USD = 0.92 Euro, 1
SGID=0.65 Euro.

Ans:-

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

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class CurrencyConverter extends JFrame {

private JTextField amountField;

private JLabel resultLabel;

public CurrencyConverter() {

setTitle("Currency Converter");

setSize(400, 200);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new FlowLayout());

JLabel instructionLabel = new JLabel("Enter Amount:");

amountField = new JTextField(10);

JButton convertButton = new JButton("Convert");

resultLabel = new JLabel("Converted Amount: ");


// Action listener for button click

convertButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

convertCurrency();

});

add(instructionLabel);

add(amountField);

add(convertButton);

add(resultLabel);

private void convertCurrency() {

try {

double amount = Double.parseDouble(amountField.getText());

StringBuilder result = new StringBuilder("<html>");

// Conversions
double usdToSgd = amount * 1.41;

double usdToEur = amount * 0.92;

double sgdToEur = amount * 0.65;

// Display results

result.append("USD: ").append(String.format("%.2f", amount)).append("<br>");

result.append("SGD: ").append(String.format("%.2f", usdToSgd)).append("<br>");

result.append("EUR: ").append(String.format("%.2f", usdToEur)).append("<br>");

result.append("SGD to EUR: ").append(String.format("%.2f",


sgdToEur)).append("</html>");

resultLabel.setText(result.toString());

} catch (NumberFormatException e) {

resultLabel.setText("Please enter a valid number.");

public static void main(String[] args) {

SwingUtilities.invokeLater(() -> {

CurrencyConverter frame = new CurrencyConverter();


frame.setVisible(true);

});

Slip no-24

Q1) Create an abstract class 'Bank' with an abstract method 'getBalance'. Rs. 100, Rs.150 and
Rs.200 are deposited in banks A, B and C respectively. 'BankA', 'BankB' and 'BankC are
subclasses of class 'Bank', each having a method named 'getBalance'. Call this method by
creating an object of each of the three classes.
Ans:
abstract class Bank {
// Abstract method to get balance
abstract int getBalance();
}

class BankA extends Bank {


private int balance;

public BankA() {
this.balance = 100; // Deposited amount
}

@Override
int getBalance() {
return balance;
}
}

class BankB extends Bank {


private int balance;

public BankB() {
this.balance = 150; // Deposited amount
}
@Override
int getBalance() {
return balance;
}
}

class BankC extends Bank {


private int balance;

public BankC() {
this.balance = 200; // Deposited amount
}

@Override
int getBalance() {
return balance;
}
}

public class BankTest {


public static void main(String[] args) {
Bank bankA = new BankA();
Bank bankB = new BankB();
Bank bankC = new BankC();

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


System.out.println("Balance in Bank B: Rs. " + bankB.getBalance());
System.out.println("Balance in Bank C: Rs. " + bankC.getBalance());
}
}

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.
Ans:-
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class ConcentricCircles extends JFrame {


public ConcentricCircles() {
setTitle("Concentric Circles");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);

// Adding mouse listener to the frame


addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
Graphics g = getGraphics();
drawCircles(g, e.getX(), e.getY());
}
});
}

private void drawCircles(Graphics g, int x, int y) {


g.setColor(Color.BLUE);
g.drawOval(x - 50, y - 50, 100, 100); // Outer circle
g.setColor(Color.GREEN);
g.drawOval(x - 30, y - 30, 60, 60); // Middle circle
g.setColor(Color.RED);
g.drawOval(x - 10, y - 10, 20, 20); // Inner circle
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
ConcentricCircles frame = new ConcentricCircles();
frame.setVisible(true);
});
}
}
Slip no-25

Q1) Create a class Student(rollno, name,class, per), to read student information from the
console and display them (Using BufferedReader class)
Ans:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Student {
private int rollNo;
private String name;
private String className;
private double percentage;

public void readStudentInfo() throws IOException {


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

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


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

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


name = reader.readLine();

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


className = reader.readLine();

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


percentage = Double.parseDouble(reader.readLine());
}

public void displayStudentInfo() {


System.out.println("Roll No: " + rollNo);
System.out.println("Name: " + name);
System.out.println("Class: " + className);
System.out.println("Percentage: " + percentage);
}
}

public class StudentTest {


public static void main(String[] args) {
Student student = new Student();
try {
student.readStudentInfo();
student.displayStudentInfo();
} catch (IOException e) {
System.out.println("An error occurred while reading input.");
}
}
}
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

Ans:

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class UserInfoForm extends JFrame {

private JTextField nameField;

private JTextField classField;

private JTextArea hobbiesArea;

private JButton submitButton;

public UserInfoForm() {

setTitle("User Information Form");

setSize(400, 300);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new GridLayout(5, 1));


// Name input

nameField = new JTextField();

add(new JLabel("Enter Name:"));

add(nameField);

// Class input

classField = new JTextField();

add(new JLabel("Enter Class:"));

add(classField);

// Hobbies input

hobbiesArea = new JTextArea();

add(new JLabel("Enter Hobbies (comma separated):"));

add(hobbiesArea);

// Submit button

submitButton = new JButton("Submit");

submitButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

displayInfo();

}
});

add(submitButton);

private void displayInfo() {

String name = nameField.getText();

String className = classField.getText();

String hobbies = hobbiesArea.getText();

String message = "Name: " + name + "\nClass: " + className + "\nHobbies: " + hobbies;

JOptionPane.showMessageDialog(this, message, "User Information",


JOptionPane.INFORMATION_MESSAGE);

public static void main(String[] args) {

SwingUtilities.invokeLater(() -> {

UserInfoForm form = new UserInfoForm();

form.setVisible(true);

});

Slip no-26
Q1) Define a Item class (item_number, item_name, item_price). Define a default and
parameterized constructor. Keep a count of objects created. Create objects using
parameterized constructor and display the object count after each object is created. (Use static
member and method). Also display the contents of each object.

Ans:

class Item {

private static int objectCount = 0;

private int itemNumber;

private String itemName;

private double itemPrice;

// Default Constructor

public Item() {

objectCount++;

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

this.itemNumber = itemNumber;

this.itemName = itemName;

this.itemPrice = itemPrice;

objectCount++;

System.out.println("Object Count after creation: " + objectCount);

// Static method to get object count

public static int getObjectCount() {

return objectCount;

// 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);

// Test the Item class

public class ItemTest {

public static void main(String[] args) {

Item item1 = new Item(1, "Item One", 10.99);

item1.display();

Item item2 = new Item(2, "Item Two", 20.49);

item2.display();
System.out.println("Total Items Created: " + Item.getObjectCount());

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.
Ans:
import java.io.*;
import java.util.*;

class Donor {
String name;
int age;
String address;
String contactNumber;
String bloodGroup;
Date lastDonation;

// Constructor
public Donor(String name, int age, String address, String contactNumber, String bloodGroup,
Date lastDonation) {
this.name = name;
this.age = age;
this.address = address;
this.contactNumber = contactNumber;
this.bloodGroup = bloodGroup;
this.lastDonation = lastDonation;
}

// Method to check eligibility


public boolean isEligible() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -6);
return lastDonation.before(cal.getTime());
}

@Override
public String toString() {
return name + "," + age + "," + address + "," + contactNumber + "," + bloodGroup + "," +
lastDonation;
}
}

// Test Donor class


public class DonorTest {
public static void main(String[] args) throws IOException {
List<Donor> donors = new ArrayList<>();
// Add donor objects (you may want to replace this with actual data)
donors.add(new Donor("John Doe", 30, "Pune", "1234567890", "A+ve", new
Date(System.currentTimeMillis() - 200L * 24 * 60 * 60 * 1000)));
donors.add(new Donor("Jane Smith", 28, "Pune", "0987654321", "A+ve", new
Date(System.currentTimeMillis() - 100L * 24 * 60 * 60 * 1000)));

// Write donors to file


try (BufferedWriter writer = new BufferedWriter(new FileWriter("donors.txt"))) {
for (Donor donor : donors) {
writer.write(donor.toString());
writer.newLine();
}
}

// Read donors from file


try (BufferedReader reader = new BufferedReader(new FileReader("donors.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
String[] data = line.split(",");
Donor donor = new Donor(data[0], Integer.parseInt(data[1]), data[2], data[3], data[4],
new Date(data[5]));
if (donor.bloodGroup.equals("A+ve") && donor.isEligible()) {
System.out.println(donor);
}
}
}
}
}

Slip no-27

Q1) Define an Employee class with suitable attributes having getSalary() method, which returns
salary withdrawn by a particular employee. Write a class Manager which extends a class
Employee, override the getSalary() method, which will return salary of manager by adding
traveling allowance, house rent allowance etc.
Ans:
class Employee {
private double salary;

public Employee(double salary) {


this.salary = salary;
}

public double getSalary() {


return salary;
}
}

class Manager extends Employee {


private double travelingAllowance;
private double houseRentAllowance;

public Manager(double salary, double travelingAllowance, double houseRentAllowance) {


super(salary);
this.travelingAllowance = travelingAllowance;
this.houseRentAllowance = houseRentAllowance;
}

@Override
public double getSalary() {
return super.getSalary() + travelingAllowance + houseRentAllowance;
}
}

// Test Employee and Manager classes


public class EmployeeTest {
public static void main(String[] args) {
Employee emp = new Employee(30000);
System.out.println("Employee Salary: " + emp.getSalary());

Manager mgr = new Manager(50000, 5000, 2000);


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

Q2) Write a program to accept a string as command line argument and check whether it is a file
or directory. Also perform operations as follows:

i) If it is a directory, delete all text files in that directory. Confirm delete operation from
user before deleting text files. Also, display a count showing the number of files
deleted, if any, from the directory. ii)If it is a file display various details of that file.
Ans:
import java.util.*;
import java.io.*;
class slip27_2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String fname = args[0];
File f = new File(fname);
if (f.isFile()) {
System.out.println("File Name:" + f.getName());
System.out.println("File Length:" + f.length());
System.out.println("File Absolute Path:" + f.getAbsolutePath());
System.out.println("File Path:" + f.getPath());
} else if (f.isDirectory()) {
System.out.println("Sure you want Delete All Files (Press 1)");
int n = sc.nextInt();
if (n == 1) {
String[] s1 = f.list();
String a = ".txt";
for (String str : s1) {
System.out.println(str);
if (str.endsWith(a)) {
File f1 = new File(fname, str);
System.out.println(str + "-->Deleted");
f1.delete();
}
}
} else {
System.out.println("OKKKK");
}
}
}
}
Slip no-28

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.
Ans:
import java.io.File;
import java.util.Scanner;

public class FileInformationChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the file name (with path if necessary): ");
String fileName = scanner.nextLine();

File file = new File(fileName);

if (file.exists()) {
System.out.println("File exists: " + file.exists());
System.out.println("Readable: " + file.canRead());
System.out.println("Writable: " + file.canWrite());
System.out.println("File type: " + (file.isFile() ? "File" : (file.isDirectory() ? "Directory" :
"Unknown")));
System.out.println("File length: " + file.length() + " bytes");
} else {
System.out.println("The specified file does not exist.");
}

scanner.close();
}
}

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".
Ans:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SwingTemperatureConverter {

public static void main(String[] args) {


JFrame frame = new JFrame("Temperature Converter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 150);
frame.setLayout(new FlowLayout());

JLabel label = new JLabel("Enter temperature:");


JTextField textField = new JTextField(10);
JButton celsiusButton = new JButton("To Celsius");
JButton fahrenheitButton = new JButton("To Fahrenheit");
JLabel resultLabel = new JLabel("");

celsiusButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
double fahrenheit = Double.parseDouble(textField.getText());
double celsius = (fahrenheit - 32) * 5 / 9;
resultLabel.setText("Celsius: " + String.format("%.1f", celsius));
} catch (NumberFormatException ex) {
resultLabel.setText("Invalid input!");
}
}
});

fahrenheitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
double celsius = Double.parseDouble(textField.getText());
double fahrenheit = (celsius * 9 / 5) + 32;
resultLabel.setText("Fahrenheit: " + String.format("%.1f", fahrenheit));
} catch (NumberFormatException ex) {
resultLabel.setText("Invalid input!");
}
}
});

frame.add(label);
frame.add(textField);
frame.add(celsiusButton);
frame.add(fahrenheitButton);
frame.add(resultLabel);

frame.setVisible(true);
}
}
Slip no-29

Q1) Write a program to create a class Customer(custno,custname,contactnumber,custaddr).


Write a method to search the customer name with given contact number and display the details.
Ans:
import java.util.Scanner;

class Customer {
int cno;
String cname, cmob, cadd;

public static void main(String[] args) {


int i = 0;
Scanner sc = new Scanner(System.in);
Customer ob[] = new Customer[5];

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


System.out.println("Enter cno, cname, cmob, cadd");
ob[i] = new Customer();
ob[i].cno = sc.nextInt();
ob[i].cname = sc.next();
ob[i].cmob = sc.next();
ob[i].cadd = sc.next();
}

System.out.print("Enter mobile number to search: ");


String mb = sc.next(); // Added to get user input for mobile number

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


if (ob[i].cmob.equals(mb)) { // Corrected the comparison
System.out.println("Name: " + ob[i].cname);
break; // Optional: Exit the loop once found
}
}
sc.close(); // Close the scanner to prevent resource leak
}
}

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.
Ans:-
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

// Superclass
class Vehicle {
String company;
double price;

Vehicle(String company, double price) {


this.company = company;
this.price = price;
}

void displayInfo() {
System.out.println("Company: " + company);
System.out.println("Price: " + price);
}
}

// Subclass for light motor vehicles


class LightMotorVehicle extends Vehicle {
double mileage;

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


super(company, price);
this.mileage = mileage;
}
@Override
void displayInfo() {
super.displayInfo();
System.out.println("Mileage: " + mileage + " km/l");
}
}

// Subclass for heavy motor vehicles


class HeavyMotorVehicle extends Vehicle {
double capacityInTons;

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


super(company, price);
this.capacityInTons = capacityInTons;
}

@Override
void displayInfo() {
super.displayInfo();
System.out.println("Capacity: " + capacityInTons + " tons");
}
}

public class VehicleInfo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Vehicle> vehicles = new ArrayList<>();

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


int n = scanner.nextInt();
for (int i = 0; i < n; i++) {
System.out.print("Enter type of vehicle (1 for Light Motor Vehicle, 2 for Heavy Motor
Vehicle): ");
int type = scanner.nextInt();

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


String company = scanner.next();

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


double price = scanner.nextDouble();

if (type == 1) {
System.out.print("Enter mileage: ");
double mileage = scanner.nextDouble();
vehicles.add(new LightMotorVehicle(company, price, mileage));
} else if (type == 2) {
System.out.print("Enter capacity in tons: ");
double capacityInTons = scanner.nextDouble();
vehicles.add(new HeavyMotorVehicle(company, price, capacityInTons));
} else {
System.out.println("Invalid vehicle type. Please enter 1 or 2.");
i--; // Decrement i to repeat this iteration
}
}

System.out.println("\nVehicle Information:");
for (Vehicle vehicle : vehicles) {
vehicle.displayInfo();
System.out.println();
}

scanner.close();
}
}

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

Ans:
import java.util.Scanner;

class Person {
String personName;
String aadharNo;
String panNo;

// Constructor to initialize Person object


Person(String personName, String aadharNo, String panNo) {
this.personName = personName; // Using 'this' to refer to class variables
this.aadharNo = aadharNo;
this.panNo = panNo;
}

// Method to display person information


void displayInfo() {
System.out.println("Person Name: " + personName);
System.out.println("Aadhar Number: " + aadharNo);
System.out.println("PAN Number: " + panNo);
System.out.println();
}
}

public class PersonInfo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Person[] persons = new Person[5];

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


System.out.print("Enter Name: ");
String name = scanner.nextLine();

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


String aadhar = scanner.nextLine();

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


String pan = scanner.nextLine();

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


}

System.out.println("\nPerson Information:");
for (Person person : persons) {
person.displayInfo(); // Displaying information for each person
}

scanner.close();
}
}
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.
Ans:-
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class DivisionCalculator {


public static void main(String[] args) {
// Creating the frame
JFrame frame = new JFrame("Integer Division Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
frame.setLayout(null);

// Creating components
JLabel label1 = new JLabel("Number 1:");
label1.setBounds(20, 20, 100, 30);
JTextField number1Field = new JTextField();
number1Field.setBounds(120, 20, 150, 30);

JLabel label2 = new JLabel("Number 2:");


label2.setBounds(20, 60, 100, 30);
JTextField number2Field = new JTextField();
number2Field.setBounds(120, 60, 150, 30);

JButton divideButton = new JButton("Divide");


divideButton.setBounds(120, 100, 150, 30);
JLabel resultLabel = new JLabel("Result:");
resultLabel.setBounds(20, 140, 100, 30);
JTextField resultField = new JTextField();
resultField.setBounds(120, 140, 150, 30);
resultField.setEditable(false);

// Adding components to the frame


frame.add(label1);
frame.add(number1Field);
frame.add(label2);
frame.add(number2Field);
frame.add(divideButton);
frame.add(resultLabel);
frame.add(resultField);

// Action listener for the button


divideButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
// Parsing inputs
int number1 = Integer.parseInt(number1Field.getText());
int number2 = Integer.parseInt(number2Field.getText());

// Performing division
if (number2 == 0) {
throw new ArithmeticException("Cannot divide by zero");
}

int result = number1 / number2;


resultField.setText(String.valueOf(result));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(frame, "Please enter valid integers.", "Input
Error", JOptionPane.ERROR_MESSAGE);
} catch (ArithmeticException ex) {
JOptionPane.showMessageDialog(frame, ex.getMessage(), "Arithmetic Error",
JOptionPane.ERROR_MESSAGE);
}
}
});

// Setting the frame to be visible


frame.setVisible(true);
}
}

You might also like