[Go to site: main page, start]

0% found this document useful (0 votes)
2 views27 pages

Java User-Defined Exceptions & Discounts

Uploaded by

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

Java User-Defined Exceptions & Discounts

Uploaded by

seenuboost
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

SET-A

1. Write a Java program that demonstrates user-defined exception Invalid


PasswordException. Create a method login(String password) that
throws Invalid PasswordException if the entered password is not
"admin123". Handle the exception in the main method and display a
suitable error message. If the password is correct, display" Login
Successful
CODING:
// Program 1: User-defined Exception for Invalid Password
import [Link];

// Step 1: Create custom exception class


class InvalidPasswordException extends Exception {
public InvalidPasswordException(String message) {
super(message);
}
}

public class LoginDemo {


// Step 2: Create login method
static void login(String password) throws InvalidPasswordException {
if (![Link]("admin123")) {
throw new InvalidPasswordException("Error: Invalid Password! Please
try again.");
} else {
[Link]("Login Successful");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter password: ");


String pass = [Link]();

try {
login(pass); // calling login method
} catch (InvalidPasswordException e) {
[Link]([Link]());
}
}
}

2. Create an abstract class Customer with an abstract method calculate


Discount(double billAmount). Subclasses GIVE CORRECT CODE WITH
ANSWERS..AND THE CODE SHOULD NOT BE TOO TECHNICAL IT SHOULD
BE CLEAR AND SIMPLE RegularCustomer discount 5% of bill amount
PremiumCustomer discount 10% of bill amount VIPCustomer discount
15% of bill amount Demonstrate runtime polymorphism by using a
customer reference to call calculate Discount() for different customer
objects.

CODE:
// Program 2: Abstract class Customer with Discounts
import [Link];
// Step 1: Abstract class
abstract class Customer {
abstract void calculateDiscount(double billAmount);
}

// Step 2: Subclasses
class RegularCustomer extends Customer {
void calculateDiscount(double billAmount) {
double discount = billAmount * 0.05; // 5% discount
[Link]("Regular Customer Discount: " + discount);
[Link]("Final Bill: " + (billAmount - discount));
}
}

class PremiumCustomer extends Customer {


void calculateDiscount(double billAmount) {
double discount = billAmount * 0.10; // 10% discount
[Link]("Premium Customer Discount: " + discount);
[Link]("Final Bill: " + (billAmount - discount));
}
}

class VIPCustomer extends Customer {


void calculateDiscount(double billAmount) {
double discount = billAmount * 0.15; // 15% discount
[Link]("VIP Customer Discount: " + discount);
[Link]("Final Bill: " + (billAmount - discount));
}
}

// Step 3: Main class


public class DiscountDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter Bill Amount: ");


double amount = [Link]();

// Runtime Polymorphism
Customer c;

c = new RegularCustomer(); // Customer reference points to


RegularCustomer
[Link](amount);

c = new PremiumCustomer(); // Now points to PremiumCustomer


[Link](amount);

c = new VIPCustomer(); // Now points to VIPCustomer


[Link](amount);
}
}
SET-B

1. Define interface Engine with method startEngine(). Define interface


Brake with method applyBrake(). Class Car implements both. Create n
car objects (with different models) and show them starting and
braking.
CODE:
// Program 1: Interface Example
import [Link];

// Step 1: Define Engine interface


interface Engine {
void startEngine();
}

// Step 2: Define Brake interface


interface Brake {
void applyBrake();
}

// Step 3: Car class implements both


class Car implements Engine, Brake {
String model;

Car(String model) {
[Link] = model;
}

public void startEngine() {


[Link](model + " Engine Started...");
}

public void applyBrake() {


[Link](model + " Brake Applied...");
}
}

// Step 4: Main class


public class CarDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter number of cars: ");


int n = [Link]();
[Link](); // consume newline

Car[] cars = new Car[n];

// Create car objects


for (int i = 0; i < n; i++) {
[Link]("Enter model for Car " + (i + 1) + ": ");
String model = [Link]();
cars[i] = new Car(model);
}

// Demonstrate engine and brake


[Link]("\n--- Car Operations ---");
for (Car car : cars) {
[Link]();
[Link]();
[Link]();
}
}
}
2. In a scientific calculator app, two independent threads perform different
operations simultaneously:
Thread 1 (Fibonacci) prints the first n Fibonacci numbers (e.g., n-70, 1, 1, 2, 3,
5, 8). I
Thread 2 (Square Sum) → calculates the sum of squares of the first n natural
numbers (e.g., n=512+22+32+42+5=55).
Write a Java program using threads to perform these tasks independently.

CODE:
// Program 2: Multithreading Example
import [Link];

// Thread 1 → Fibonacci
class FibonacciThread extends Thread {
int n;

FibonacciThread(int n) {
this.n = n;
}

public void run() {


[Link]("Fibonacci Series (first " + n + " numbers):");
int a = 0, b = 1;
[Link](a + " " + b + " ");
for (int i = 3; i <= n; i++) {
int c = a + b;
[Link](c + " ");
a = b;
b = c;
}
[Link]("\n");
}
}

// Thread 2 → Square Sum


class SquareSumThread extends Thread {
int n;

SquareSumThread(int n) {
this.n = n;
}

public void run() {


int sum = 0;
[Link]("Squares of first " + n + " natural numbers:");
for (int i = 1; i <= n; i++) {
[Link](i + "^2 ");
sum += i * i;
}
[Link]("\nSum of Squares = " + sum);
}
}

// Main class
public class CalculatorThreads {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter n value: ");


int n = [Link]();

FibonacciThread fThread = new FibonacciThread(n);


SquareSumThread sThread = new SquareSumThread(n);

// Start both threads


[Link]();
[Link]();
}
}
SET-C
1. Create a class InterestCalculator with overloaded methods named
calculateInterest(). calculatelnterest(double principal, double rate, int
time) → calculates Simple Interest = (PxRxT)/100,
calculateInterest(double principal, double rate, int time, int n)→
calculates Compound Interest Px (1+R/n) (nxT) P,
calculateInterest(double principal) assumes a fixed interest rate of 5%
for 1 year and calculates SI. Demonstrate compile-time polymorphism
by calling different versions of calculateInterest().

CODE:
// Program 1: Interest Calculator (Method Overloading)
class InterestCalculator {

// Method 1: Simple Interest


double calculateInterest(double principal, double rate, int time) {
double si = (principal * rate * time) / 100;
return si;
}

// Method 2: Compound Interest


double calculateInterest(double principal, double rate, int time, int n) {
double ci = principal * [Link]((1 + rate / (100 * n)), n * time) - principal;
return ci;
}
// Method 3: Fixed 5% SI for 1 year
double calculateInterest(double principal) {
double si = (principal * 5 * 1) / 100;
return si;
}
}

// Main class
public class InterestDemo {
public static void main(String[] args) {
InterestCalculator ic = new InterestCalculator();

// Demonstrating compile-time polymorphism


double si1 = [Link](10000, 8, 2); // SI
double ci1 = [Link](10000, 8, 2, 4); // CI
double si2 = [Link](5000); // Fixed SI

[Link]("Simple Interest (P=10000, R=8%, T=2) = " + si1);


[Link]("Compound Interest (P=10000, R=8%, T=2, n=4) = " +
ci1);
[Link]("Fixed 5% SI for P=5000, T=1 = " + si2);
}
}
2. Create a Java interface called FileOperations declaring the common
methods: open() - to open the file. close() to close the file. getSize() to
get the file size in MB. Implement classes TextFile, ImageFile, and
VideoFile implementing the FileOperations interface. Add their specific
methods as described. Write a main method to: demonstrate
polymorphism by storing them in a FileOperations and calling open(),
close(), and getSize() for all files.
CODE:
// Program 2: FileOperations Interface
interface FileOperations {
void open();
void close();
double getSize(); // size in MB
}

// TextFile class
class TextFile implements FileOperations {
private String name;
private double size;

TextFile(String name, double size) {


[Link] = name;
[Link] = size;
}
public void open() {
[Link]("Opening Text File: " + name);
}

public void close() {


[Link]("Closing Text File: " + name);
}

public double getSize() {


return size;
}

// Specific method
void wordCount() {
[Link]("Counting words in " + name);
}
}

// ImageFile class
class ImageFile implements FileOperations {
private String name;
private double size;

ImageFile(String name, double size) {


[Link] = name;
[Link] = size;
}

public void open() {


[Link]("Opening Image File: " + name);
}

public void close() {


[Link]("Closing Image File: " + name);
}

public double getSize() {


return size;
}

// Specific method
void showResolution() {
[Link]("Resolution of " + name + " is 1920x1080");
}
}

// VideoFile class
class VideoFile implements FileOperations {
private String name;
private double size;

VideoFile(String name, double size) {


[Link] = name;
[Link] = size;
}

public void open() {


[Link]("Playing Video File: " + name);
}

public void close() {


[Link]("Stopping Video File: " + name);
}

public double getSize() {


return size;
}

// Specific method
void playDuration() {
[Link]("Video duration of " + name + " is 2 hours");
}
}

// Main class
public class FileDemo {
public static void main(String[] args) {
FileOperations[] files = new FileOperations[3];
files[0] = new TextFile("[Link]", 1.2);
files[1] = new ImageFile("[Link]", 2.5);
files[2] = new VideoFile("movie.mp4", 700.0);

[Link]("--- File Operations ---");


for (FileOperations f : files) {
[Link]();
[Link]("File Size: " + [Link]() + " MB");
[Link]();
[Link]();
}
}
}

SET-D

Subclassex 1. Create a base class Employee with a method


calculateSalary() Full Time Employee calculates salary as basic bonus, Part
Time Employee calculates salary as hours Worked hourlyRate,
ContractEmployee calculates salary as a fixed contract Amount
Demonstrate runtime polymorphism by creating an Employee reference
pointing to different employee objects and calling calculateSalary().
CODE:
// Program 1: Employee Salary Calculation using Runtime Polymorphism
class Employee {
String name;
Employee(String name) {
[Link] = name;
}

double calculateSalary() {
return 0.0;
}
}

// Full-time employee
class FullTimeEmployee extends Employee {
double basic, bonus;

FullTimeEmployee(String name, double basic, double bonus) {


super(name);
[Link] = basic;
[Link] = bonus;
}

@Override
double calculateSalary() {
return basic + bonus;
}
}

// Part-time employee
class PartTimeEmployee extends Employee {
int hoursWorked;
double hourlyRate;

PartTimeEmployee(String name, int hoursWorked, double hourlyRate) {


super(name);
[Link] = hoursWorked;
[Link] = hourlyRate;
}

@Override
double calculateSalary() {
return hoursWorked * hourlyRate;
}
}

// Contract employee
class ContractEmployee extends Employee {
double contractAmount;

ContractEmployee(String name, double contractAmount) {


super(name);
[Link] = contractAmount;
}

@Override
double calculateSalary() {
return contractAmount;
}
}

// Main class
public class EmployeeDemo {
public static void main(String[] args) {
Employee e;

e = new FullTimeEmployee("Alice", 20000, 5000);


[Link]([Link] + " Salary: " + [Link]());

e = new PartTimeEmployee("Bob", 40, 200);


[Link]([Link] + " Salary: " + [Link]());

e = new ContractEmployee("Charlie", 30000);


[Link]([Link] + " Salary: " + [Link]());
}
}
2. Grading system uses two independent threads to evaluate a student's
performance

Thread 1 (Total Marks) calculates the total marks obtained in 5 subjects


(eg, 30, 75, 90, 85, 70→Total 400).
Thread 2 (Percentage) Write a Java program using threads calculates the
percentage marks (Total 500-100-80%)

CODE:
// Program 2: Grading System using Threads
class TotalMarksThread extends Thread {
int[] marks;
int total = 0;

TotalMarksThread(int[] marks) {
[Link] = marks;
}

public void run() {


for (int m : marks) {
total += m;
}
[Link]("Total Marks = " + total);
}

public int getTotal() {


return total;
}
}

class PercentageThread extends Thread {


int total;
int maxMarks;

PercentageThread(int total, int maxMarks) {


[Link] = total;
[Link] = maxMarks;
}

public void run() {


double percentage = (total * 100.0) / maxMarks;
[Link]("Percentage = " + percentage + "%");
}
}

public class GradingSystem {


public static void main(String[] args) {
int[] marks = {30, 75, 90, 85, 70}; // Example marks
int maxMarks = 500;

TotalMarksThread t1 = new TotalMarksThread(marks);


[Link]();

try {
[Link](); // wait for total calculation before percentage
} catch (InterruptedException e) {
[Link]();
}
PercentageThread t2 = new PercentageThread([Link](),
maxMarks);
[Link]();
}
}
SET-F

1. Define interface Walkable with method walk(). Define interface


Speakable with method speak(). Class Robot implements both.
Create n robots (objects), each with unique abilities, and show them
walking and speaking.
CODE:
// Program 1: Robot implementing Walkable and Speakable
import [Link];

// Step 1: Define interfaces


interface Walkable {
void walk();
}

interface Speakable {
void speak();
}

// Step 2: Robot class implements both


class Robot implements Walkable, Speakable {
String name;
String ability;

Robot(String name, String ability) {


[Link] = name;
[Link] = ability;
}

public void walk() {


[Link](name + " is walking with " + ability + " speed.");
}

public void speak() {


[Link](name + " says: 'Hello, I am a robot with " + ability + "
ability!'");
}
}

// Step 3: Main class


public class RobotDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter number of robots: ");


int n = [Link]();
[Link](); // consume newline
Robot[] robots = new Robot[n];

// Create robots
for (int i = 0; i < n; i++) {
[Link]("Enter name for Robot " + (i + 1) + ": ");
String name = [Link]();

[Link]("Enter unique ability for " + name + ": ");


String ability = [Link]();

robots[i] = new Robot(name, ability);


}

// Show abilities
[Link]("\n--- Robot Demonstration ---");
for (Robot r : robots) {
[Link]();
[Link]();
[Link]();
}
}
}

2. A finance calculator uses two independent threads to perform


different calculations on financial data: A
Thread 1 (Simple Interest) calculates simple interest.
Thread 4 (EMI Calculator) calculates monthly EMI using PxRx(1+R) EMI =
(1+R)-1 where P-Loan amount, R-monthly interest rate, N=number of month
CODE:
// Program 2: Finance Calculator using Threads
import [Link];

// Thread 1 → Simple Interest


class SimpleInterestThread extends Thread {
double p, r;
int t;

SimpleInterestThread(double p, double r, int t) {


this.p = p;
this.r = r;
this.t = t;
}

public void run() {


double si = (p * r * t) / 100;
[Link]("Simple Interest = " + si);
}
}

// Thread 2 → EMI Calculator


class EMIThread extends Thread {
double p, annualRate;
int n;
EMIThread(double p, double annualRate, int n) {
this.p = p;
[Link] = annualRate;
this.n = n;
}

public void run() {


double R = annualRate / (12 * 100); // monthly interest rate
double emi = (p * R * [Link](1 + R, n)) / ([Link](1 + R, n) - 1);
[Link]("Monthly EMI = " + emi);
}
}

// Main class
public class FinanceCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Input for SI
[Link]("Enter Principal for SI: ");
double p1 = [Link]();
[Link]("Enter Rate of Interest (annual %): ");
double r1 = [Link]();
[Link]("Enter Time (in years): ");
int t1 = [Link]();
// Input for EMI
[Link]("\nEnter Loan Amount for EMI: ");
double p2 = [Link]();
[Link]("Enter Annual Interest Rate (in %): ");
double r2 = [Link]();
[Link]("Enter Number of Months: ");
int n = [Link]();

// Create threads
SimpleInterestThread siThread = new SimpleInterestThread(p1, r1, t1);
EMIThread emiThread = new EMIThread(p2, r2, n);

// Start threads
[Link]();
[Link]();
}
}

You might also like