Java slips solution sem 5
Java slips solution sem 5
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.");
}
}
}
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;
}
}
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.
Ans:-
if (args.length < 4) {
return;
}
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;
CricketPlayer.sortPlayers(players);
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;
Arrays.sort(cities);
System.out.println("Cities in ascending order:");
for (String city : cities) {
System.out.println(city);
}
}
}
class Patient {
String patient_name;
int patient_age;
double patient_oxy_level;
double patient_HRCT_report;
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;
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.*;
LoginScreenAWT() {
setTitle("Login Screen");
setSize(400, 300);
setLayout(new GridLayout(4, 2));
loginButton.addActionListener(this);
clearButton.addActionListener(this);
setVisible(true);
}
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("");
}
}
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;
}
}
void displayDetails() {
System.out.println("Continent: " + continentName);
System.out.println("Country: " + countryName);
System.out.println("State: " + stateName);
}
}
Q2) Write a menu driven program to perform the following operations on multidimensional array
ie matrices:
Addition
Multiplication
Exit
Ans:-
import java.util.Scanner;
matrix1[i][j] = sc.nextInt();
matrix2[i][j] = sc.nextInt();
int choice;
do {
System.out.println("1. Addition");
System.out.println("2. Multiplication");
System.out.println("3. Exit");
choice = sc.nextInt();
switch (choice) {
case 1:
System.out.println("Sum of matrices:");
System.out.println();
break;
case 2:
product[i][j] = 0;
System.out.println("Product of matrices:");
System.out.println();
break;
case 3:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice.");
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;
@Override
public String toString() {
return "Employee ID: " + empId + "\nEmployee Name: " + empName +
"\nEmployee Designation: " + empDesignation + "\nEmployee Salary: " + empSal;
}
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;
@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);
}
}
@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);
}
}
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;
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.*;
String line;
while ((line = fileReader.readLine()) != null) {
content.append(line).append("\n");
}
fileReader.close();
Slip no-8
Q1) Create a class Sphere, to calculate the volume and surface area of sphere.
MouseEventDemoAWT() {
tf = new TextField();
tf.setBounds(50, 50, 200, 30);
add(tf);
addMouseListener(this);
addMouseMotionListener(this);
setSize(400, 400);
setLayout(null);
setVisible(true);
}
Slip no-9
import java.util.Scanner;
class Clock {
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
} else {
return (hours >= 0 && hours < 24) && (minutes >= 0 && minutes < 60) && (seconds >= 0
&& seconds < 60);
}
public void displayTime() {
try {
clock.displayTime();
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
public Product() {
objectCount++;
}
p1.displayProductDetails();
p2.displayProductDetails();
p3.displayProductDetails();
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);
}
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];
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
}
}
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();
}
//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;
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 {
this.cno = cno;
this.cname = cname;
this.caddr = caddr;
System.out.println("College No: " + cno + ", Name: " + cname + ", Address: " + caddr);
public Department(int cno, String cname, String caddr, int dno, String dname) {
this.dno = dno;
this.dname = dname;
}
displayCollegeDetails();
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 {
public SimpleCalculator() {
setTitle("Simple Calculator");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textField.setEditable(false);
add(textField);
addButton(String.valueOf(i));
addButton("0");
addButton("+");
addButton("-");
addButton("*");
addButton("/");
addButton("=");
addButton("C");
setVisible(true);
button.addActionListener(this);
add(button);
@Override
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 "+":
break;
case "-":
break;
case "*":
break;
case "/":
break;
textField.setText(String.valueOf(result));
} else {
operator = command;
num1 = Double.parseDouble(textField.getText());
textField.setText("");
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;
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;
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;
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
package SY;
this.computerTotal = computerTotal;
this.mathsTotal = mathsTotal;
this.electronicsTotal = electronicsTotal;
return computerTotal;
}
// File: TY/TYMarks.java
package TY;
this.theory = theory;
this.practicals = 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 {
this.rollNumber = rollNumber;
this.name = name;
this.syMarks = syMarks;
this.tyMarks = tyMarks;
return "B";
return "C";
} else {
return "FAIL";
@Override
return "Student Roll Number: " + rollNumber + ", Name: " + name + ", Grade: " +
calculateGrade();
int n = scanner.nextInt();
System.out.print("Name: ");
System.out.println("\nStudent Results:");
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.*;
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;
}
String line;
while ((line = fileReader.readLine()) != null) {
fileWriter.write(line);
fileWriter.newLine();
}
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;
}
}
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);
}
scanner.close();
}
}
Ans:-
import java.awt.*;
import java.awt.event.*;
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);
// 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.");
}
}
class Customer {
String name;
String phoneNumber;
@Override
public void display() {
super.display();
System.out.println("Account Number: " + accNo);
System.out.println("Balance: " + balance);
}
}
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);
}
}
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 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);
// 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);
}
}
Slip no18
Ans:-
import java.awt.*;
import javax.swing.*;
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.setVisible(true);
}
}
class CricketPlayer {
String name;
int noOfInnings;
int noOfTimesNotOut;
int totalRuns;
double batAvg;
@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
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;
System.out.print("Enter the number of rows and columns of the matrix (n x n): ");
int n = scanner.nextInt();
matrix[i][j] = scanner.nextInt();
int diagonalSum = 0;
// Calculating the sum of diagonal elements
if (n % 2 != 0) {
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 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"
};
subjectComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selectedSubject = (String) subjectComboBox.getSelectedItem();
selectedSubjectField.setText(selectedSubject);
}
});
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;
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;
(2.Maximum.java)
package Operation;
// Testing Addition
int sum = addition.add(5, 10);
float difference = addition.subtract(5.5f, 3.5f);
// 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;
}
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++;
}
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;
@Override
public void printArea() {
System.out.println("Area of Rectangle: " + (dimension1 * dimension2));
}
}
@Override
public void printArea() {
System.out.println("Area of Triangle: " + (0.5 * dimension1 * dimension2));
}
}
@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 MouseEventDemo() {
setTitle("Mouse Event Demo");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
@Override
public void mouseEntered(MouseEvent e) {
label.setText("Mouse Entered");
}
@Override
public void mouseExited(MouseEvent e) {
label.setText("Mouse Exited");
}
@Override
public void mousePressed(MouseEvent e) {
label.setText("Mouse Pressed");
}
@Override
public void mouseReleased(MouseEvent e) {
label.setText("Mouse Released");
}
});
}
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
}
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 CurrencyConverter() {
setTitle("Currency Converter");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
convertButton.addActionListener(new ActionListener() {
convertCurrency();
});
add(instructionLabel);
add(amountField);
add(convertButton);
add(resultLabel);
try {
// Conversions
double usdToSgd = amount * 1.41;
// Display results
resultLabel.setText(result.toString());
} catch (NumberFormatException e) {
SwingUtilities.invokeLater(() -> {
});
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();
}
public BankA() {
this.balance = 100; // Deposited amount
}
@Override
int getBalance() {
return balance;
}
}
public BankB() {
this.balance = 150; // Deposited amount
}
@Override
int getBalance() {
return balance;
}
}
public BankC() {
this.balance = 200; // Deposited amount
}
@Override
int getBalance() {
return balance;
}
}
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;
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;
Ans:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public UserInfoForm() {
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(nameField);
// Class input
add(classField);
// Hobbies input
add(hobbiesArea);
// Submit button
submitButton.addActionListener(new ActionListener() {
displayInfo();
}
});
add(submitButton);
String message = "Name: " + name + "\nClass: " + className + "\nHobbies: " + hobbies;
SwingUtilities.invokeLater(() -> {
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 {
// 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++;
return objectCount;
item1.display();
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;
}
@Override
public String toString() {
return name + "," + age + "," + address + "," + contactNumber + "," + bloodGroup + "," +
lastDonation;
}
}
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;
@Override
public double getSalary() {
return super.getSalary() + travelingAllowance + houseRentAllowance;
}
}
Q2) Write a program to accept a string as command line argument and check whether it is a file
or directory. Also perform operations as follows:
i) If it is a directory, delete all text files in that directory. Confirm delete operation from
user before deleting text files. Also, display a count showing the number of files
deleted, if any, from the directory. 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;
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();
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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
class Customer {
int cno;
String cname, cmob, cadd;
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;
void displayInfo() {
System.out.println("Company: " + company);
System.out.println("Price: " + price);
}
}
@Override
void displayInfo() {
super.displayInfo();
System.out.println("Capacity: " + capacityInTons + " tons");
}
}
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;
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;
// Creating components
JLabel label1 = new JLabel("Number 1:");
label1.setBounds(20, 20, 100, 30);
JTextField number1Field = new JTextField();
number1Field.setBounds(120, 20, 150, 30);
// Performing division
if (number2 == 0) {
throw new ArithmeticException("Cannot divide by zero");
}