Java MSE1 All 108 Programs
Java MSE1 All 108 Programs
Sample Output:
Sum of 2 ints: 30
Sum of 3 ints: 60
Sum of 2 doubles: 31.0
Program 2: Area of Different Shapes
Java Code:
class AreaCalculator {
int area(int side) {
return side * side;
}
int area(int length, int breadth) {
return length * breadth;
}
double area(double radius) {
return 3.14 * radius * radius;
}
public static void main(String[] args) {
AreaCalculator ac = new AreaCalculator();
[Link]("Area of Square: " + [Link](5));
[Link]("Area of Rectangle: " + [Link](4, 6));
[Link]("Area of Circle: " + [Link](3.5));
}
}
Sample Output:
Area of Square: 25
Area of Rectangle: 24
Area of Circle: 38.465
Program 3: Student Average Marks
Java Code:
class StudentMarks {
double average(int m1, int m2) {
return (m1 + m2) / 2.0;
}
double average(int m1, int m2, int m3) {
return (m1 + m2 + m3) / 3.0;
}
double average(int m1, int m2, int m3, int m4) {
return (m1 + m2 + m3 + m4) / 4.0;
}
public static void main(String[] args) {
StudentMarks sm = new StudentMarks();
[Link]("Average of 2 subjects: " + [Link](80, 90));
[Link]("Average of 3 subjects: " + [Link](70, 80, 90));
[Link]("Average of 4 subjects: " + [Link](60, 70, 80, 90));
}
}
Sample Output:
Average of 2 subjects: 85.0
Average of 3 subjects: 80.0
Average of 4 subjects: 75.0
Program 4: Volume Calculation
Java Code:
class VolumeCalculator {
int volume(int side) {
return side * side * side;
}
int volume(int length, int breadth, int height) {
return length * breadth * height;
}
double volume(double radius, int height) {
return 3.14 * radius * radius * height;
}
public static void main(String[] args) {
VolumeCalculator vc = new VolumeCalculator();
[Link]("Volume of Cube: " + [Link](3));
[Link]("Volume of Cuboid: " + [Link](3, 4, 5));
[Link]("Volume of Cylinder: " + [Link](2.5, 7));
}
}
Sample Output:
Volume of Cube: 27
Volume of Cuboid: 60
Volume of Cylinder: 137.375
Program 5: Display Student Information
Java Code:
class StudentInfo {
void display(String name) {
[Link]("Name: " + name);
}
void display(String name, int age) {
[Link]("Name: " + name + ", Age: " + age);
}
void display(String name, int age, String department) {
[Link]("Name: " + name + ", Age: " + age + ", Dept: " +
department);
}
public static void main(String[] args) {
StudentInfo si = new StudentInfo();
[Link]("Alice");
[Link]("Bob", 20);
[Link]("Charlie", 21, "Computer Science");
}
}
Sample Output:
Name: Alice
Name: Bob, Age: 20
Name: Charlie, Age: 21, Dept: Computer Science
Program 6: Banking System – Deposit Methods
Java Code:
class BankAccount {
double balance = 5000;
void deposit(double amount) {
balance += amount;
[Link]("Cash Deposited. Balance: " + balance);
}
void deposit(double amount, String chequeNumber) {
balance += amount;
[Link]("Cheque " + chequeNumber + " Deposited. Balance: " +
balance);
}
void deposit(double amount, String upiId, boolean online) {
balance += amount;
[Link]("Online Transfer from " + upiId + ". Balance: " +
balance);
}
public static void main(String[] args) {
BankAccount ba = new BankAccount();
[Link](1000);
[Link](2000, "CHQ001");
[Link](500, "user@upi", true);
}
}
Sample Output:
Cash Deposited. Balance: 6000.0
Cheque CHQ001 Deposited. Balance: 8000.0
Online Transfer from user@upi. Balance: 8500.0
Program 7: ATM Withdrawal System
Java Code:
class ATM {
double balance = 10000;
int correctPin = 1234;
void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
[Link]("Withdrawn: " + amount + ", Balance: " + balance);
} else {
[Link]("Insufficient balance.");
}
}
void withdraw(double amount, int pin) {
if (pin != correctPin) {
[Link]("Wrong PIN!");
} else {
withdraw(amount);
}
}
void withdraw(double amount, int pin, String transactionType) {
[Link]("Transaction Type: " + transactionType);
withdraw(amount, pin);
}
public static void main(String[] args) {
ATM atm = new ATM();
[Link](2000);
[Link](3000, 1234);
[Link](1000, 9999);
[Link](500, 1234, "Savings");
}
}
Sample Output:
Withdrawn: 2000.0, Balance: 8000.0
Withdrawn: 3000.0, Balance: 5000.0
Wrong PIN!
Transaction Type: Savings
Withdrawn: 500.0, Balance: 4500.0
Program 8: Online Shopping Discount System
Java Code:
class DiscountCalculator {
double calculateDiscount(double price) {
double discount = price * 0.05;
[Link]("Final Price: " + (price - discount));
return price - discount;
}
double calculateDiscount(double price, String customerType) {
double rate = [Link]("Prime") ? 0.10 : 0.05;
double discount = price * rate;
[Link]("Final Price for " + customerType + ": " + (price -
discount));
return price - discount;
}
double calculateDiscount(double price, String customerType, boolean
festivalOffer) {
double rate = [Link]("Prime") ? 0.10 : 0.05;
if (festivalOffer) rate += 0.05;
double discount = price * rate;
[Link]("Final Price (Festival): " + (price - discount));
return price - discount;
}
public static void main(String[] args) {
DiscountCalculator dc = new DiscountCalculator();
[Link](1000);
[Link](1000, "Prime");
[Link](1000, "Regular", true);
}
}
Sample Output:
Final Price: 950.0
Final Price for Prime: 900.0
Final Price (Festival): 900.0
Program 9: Courier Delivery Charge System
Java Code:
class CourierService {
double calculateCharge(double weight) {
double charge = weight * 10;
[Link]("Charge by weight: Rs." + charge);
return charge;
}
double calculateCharge(double weight, double distance) {
double charge = weight * 10 + distance * 2;
[Link]("Charge by weight+distance: Rs." + charge);
return charge;
}
double calculateCharge(double weight, double distance, boolean express) {
double charge = weight * 10 + distance * 2;
if (express) charge += 50;
[Link]("Charge (Express): Rs." + charge);
return charge;
}
public static void main(String[] args) {
CourierService cs = new CourierService();
[Link](5);
[Link](5, 20);
[Link](5, 20, true);
}
}
Sample Output:
Charge by weight: Rs.50.0
Charge by weight+distance: Rs.90.0
Charge (Express): Rs.140.0
Program 10: Mobile Recharge System
Java Code:
class TelecomRecharge {
void recharge(String mobileNumber, double amount) {
[Link]("Recharge of Rs." + amount + " done for " +
mobileNumber);
}
void recharge(String mobileNumber, double amount, String couponCode) {
double discount = amount * 0.10;
[Link]("Coupon " + couponCode + " applied. Final: Rs." +
(amount - discount) + " for " + mobileNumber);
}
void recharge(String mobileNumber, double amount, boolean upiPayment) {
[Link]("Paid via " + (upiPayment ? "UPI" : "Card") + ". Rs." +
amount + " recharged for " + mobileNumber);
}
public static void main(String[] args) {
TelecomRecharge tr = new TelecomRecharge();
[Link]("9876543210", 299);
[Link]("9876543210", 299, "SAVE10");
[Link]("9876543210", 299, true);
}
}
Sample Output:
Recharge of Rs.299.0 done for 9876543210
Coupon SAVE10 applied. Final: Rs.269.1 for 9876543210
Paid via UPI. Rs.299.0 recharged for 9876543210
Program 11: Electricity Bill Calculator
Java Code:
class ElectricityBillCalc {
void calculateBill(int units) {
double bill = units * 5;
[Link]("Total Bill: Rs." + bill);
}
void calculateBill(int units, double tariffRate) {
double bill = units * tariffRate;
[Link]("Total Bill (Custom Tariff): Rs." + bill);
}
void calculateBill(int units, double tariffRate, double lateFee) {
double bill = units * tariffRate + lateFee;
[Link]("Total Bill (with Late Fee): Rs." + bill);
}
public static void main(String[] args) {
ElectricityBillCalc ebc = new ElectricityBillCalc();
[Link](100);
[Link](100, 6.5);
[Link](100, 6.5, 50);
}
}
Sample Output:
Total Bill: Rs.500.0
Total Bill (Custom Tariff): Rs.650.0
Total Bill (with Late Fee): Rs.700.0
Program 12: Loan Interest Calculator
Java Code:
class LoanCalculator {
void calculateInterest(double principal) {
double interest = principal * 0.10 * 1;
[Link]("Interest (default): Rs." + interest);
}
void calculateInterest(double principal, double rate) {
double interest = principal * (rate / 100) * 1;
[Link]("Interest: Rs." + interest);
}
void calculateInterest(double principal, double rate, int time) {
double interest = principal * (rate / 100) * time;
[Link]("Total Interest for " + time + " years: Rs." +
interest);
}
public static void main(String[] args) {
LoanCalculator lc = new LoanCalculator();
[Link](50000);
[Link](50000, 8.5);
[Link](50000, 8.5, 3);
}
}
Sample Output:
Interest (default): Rs.5000.0
Interest: Rs.4250.0
Total Interest for 3 years: Rs.12750.0
Program 13: Online Grocery Store
Java Code:
class GroceryStore {
void calculateTotal(double itemPrice) {
[Link]("Total: Rs." + itemPrice);
}
void calculateTotal(double itemPrice, int quantity) {
double total = itemPrice * quantity;
[Link]("Total for " + quantity + " items: Rs." + total);
}
void calculateTotal(double itemPrice, int quantity, double deliveryCharge) {
double total = itemPrice * quantity + deliveryCharge;
[Link]("Final Amount (with delivery): Rs." + total);
}
public static void main(String[] args) {
GroceryStore gs = new GroceryStore();
[Link](50);
[Link](50, 4);
[Link](50, 4, 30);
}
}
Sample Output:
Total: Rs.50.0
Total for 4 items: Rs.200.0
Final Amount (with delivery): Rs.230.0
Program 14: Bank Account System (Classes & Objects)
Java Code:
class BankAccountObj {
String accountNumber;
String accountHolderName;
double balance;
void deposit(double amount) {
balance += amount;
[Link](accountHolderName + " deposited Rs." + amount + ".
Balance: " + balance);
}
void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
[Link](accountHolderName + " withdrew Rs." + amount + ".
Balance: " + balance);
} else {
[Link]("Insufficient funds!");
}
}
void displayBalance() {
[Link](accountHolderName + "'s Balance: Rs." + balance);
}
public static void main(String[] args) {
BankAccountObj acc1 = new BankAccountObj();
[Link] = "ACC001";
[Link] = "Alice";
[Link] = 5000;
[Link](2000);
[Link](1000);
[Link]();
BankAccountObj acc2 = new BankAccountObj();
[Link] = "ACC002";
[Link] = "Bob";
[Link] = 3000;
[Link](500);
[Link]();
}
}
Sample Output:
Alice deposited Rs.2000.0. Balance: 7000.0
Alice withdrew Rs.1000.0. Balance: 6000.0
Alice's Balance: Rs.6000.0
Bob deposited Rs.500.0. Balance: 3500.0
Bob's Balance: Rs.3500.0
Program 15: Student Result System
Java Code:
class Student {
int rollNumber;
String name;
int m1, m2, m3;
int calculateTotal() {
return m1 + m2 + m3;
}
double calculateAverage() {
return calculateTotal() / 3.0;
}
void displayResult() {
[Link]("Roll: " + rollNumber + " | Name: " + name);
[Link]("Total: " + calculateTotal() + " | Average: " +
calculateAverage());
[Link]("Result: " + (calculateAverage() >= 40 ? "PASS" :
"FAIL"));
[Link]("---");
}
public static void main(String[] args) {
Student s1 = new Student();
[Link] = 1; [Link] = "Alice"; s1.m1 = 80; s1.m2 = 75; s1.m3 = 90;
Student s2 = new Student();
[Link] = 2; [Link] = "Bob"; s2.m1 = 55; s2.m2 = 60; s2.m3 = 70;
Student s3 = new Student();
[Link] = 3; [Link] = "Charlie"; s3.m1 = 30; s3.m2 = 35; s3.m3 = 25;
[Link]();
[Link]();
[Link]();
}
}
Sample Output:
Roll: 1 | Name: Alice
Total: 245 | Average: 81.67
Result: PASS
---
Roll: 2 | Name: Bob
Total: 185 | Average: 61.67
Result: PASS
---
Roll: 3 | Name: Charlie
Total: 90 | Average: 30.0
Result: FAIL
---
Program 16: Library Book Management
Java Code:
class Book {
int bookID;
String title;
String author;
boolean availabilityStatus = true;
void issueBook() {
if (availabilityStatus) {
availabilityStatus = false;
[Link](title + " issued successfully.");
} else {
[Link](title + " is not available.");
}
}
void returnBook() {
availabilityStatus = true;
[Link](title + " returned successfully.");
}
void displayBookDetails() {
[Link]("ID: " + bookID + " | Title: " + title + " | Author: " +
author + " | Available: " + availabilityStatus);
}
public static void main(String[] args) {
Book b1 = new Book();
[Link] = 101; [Link] = "Java Basics"; [Link] = "James Gosling";
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Sample Output:
ID: 101 | Title: Java Basics | Author: James Gosling | Available: true
Java Basics issued successfully.
Java Basics is not available.
Java Basics returned successfully.
ID: 101 | Title: Java Basics | Author: James Gosling | Available: true
Program 17: Mobile Phone Details
Java Code:
class MobilePhone {
String brand;
String model;
double price;
int batteryLevel;
void makeCall() {
if (batteryLevel > 10) {
[Link](brand + " " + model + " is making a call.");
} else {
[Link]("Low battery! Charge the phone.");
}
}
void chargeBattery() {
batteryLevel = 100;
[Link](brand + " " + model + " is fully charged.");
}
void displayDetails() {
[Link]("Brand: " + brand + " | Model: " + model + " | Price:
Rs." + price + " | Battery: " + batteryLevel + "%");
}
public static void main(String[] args) {
MobilePhone p1 = new MobilePhone();
[Link] = "Samsung"; [Link] = "Galaxy S23"; [Link] = 45000;
[Link] = 80;
MobilePhone p2 = new MobilePhone();
[Link] = "Apple"; [Link] = "iPhone 14"; [Link] = 79000;
[Link] = 5;
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Sample Output:
Brand: Samsung | Model: Galaxy S23 | Price: Rs.45000.0 | Battery: 80%
Samsung Galaxy S23 is making a call.
Brand: Apple | Model: iPhone 14 | Price: Rs.79000.0 | Battery: 5%
Low battery! Charge the phone.
Apple iPhone 14 is fully charged.
Apple iPhone 14 is making a call.
Program 18: Car Rental System
Java Code:
class Car {
String carNumber;
String model;
double rentalPricePerDay;
boolean availability = true;
void rentCar(int days) {
if (availability) {
availability = false;
double total = rentalPricePerDay * days;
[Link](model + " rented for " + days + " days. Total: Rs."
+ total);
} else {
[Link](model + " is not available.");
}
}
void returnCar() {
availability = true;
[Link](model + " has been returned.");
}
void displayCarDetails() {
[Link]("Car: " + model + " | Number: " + carNumber + " | Rate:
Rs." + rentalPricePerDay + "/day | Available: " + availability);
}
public static void main(String[] args) {
Car c1 = new Car();
[Link] = "MH01AB1234"; [Link] = "Swift"; [Link] =
1500;
[Link]();
[Link](3);
[Link](1);
[Link]();
}
}
Sample Output:
Car: Swift | Number: MH01AB1234 | Rate: Rs.1500.0/day | Available: true
Swift rented for 3 days. Total: Rs.4500.0
Swift is not available.
Swift has been returned.
Program 19: Online Shopping Product
Java Code:
class Product {
int productID;
String productName;
double price;
int stockQuantity;
void updateStock(int quantity) {
stockQuantity += quantity;
[Link]("Stock updated. New Stock: " + stockQuantity);
}
void purchaseProduct(int quantity) {
if (stockQuantity >= quantity) {
stockQuantity -= quantity;
[Link]("Purchased " + quantity + " units of " + productName
+ ". Remaining: " + stockQuantity);
} else {
[Link]("Not enough stock!");
}
}
void displayProductDetails() {
[Link]("ID: " + productID + " | Product: " + productName + " |
Price: Rs." + price + " | Stock: " + stockQuantity);
}
public static void main(String[] args) {
Product p1 = new Product();
[Link] = 1; [Link] = "Laptop"; [Link] = 55000;
[Link] = 10;
[Link]();
[Link](3);
[Link](5);
[Link](15);
}
}
Sample Output:
ID: 1 | Product: Laptop | Price: Rs.55000.0 | Stock: 10
Purchased 3 units of Laptop. Remaining: 7
Stock updated. New Stock: 12
Not enough stock!
Program 20: Employee Salary System
Java Code:
class Employee {
int employeeID;
String name;
double basicSalary;
double calculateSalary() {
double hra = basicSalary * 0.20;
double da = basicSalary * 0.10;
return basicSalary + hra + da;
}
void displayEmployeeDetails() {
[Link]("ID: " + employeeID + " | Name: " + name + " | Basic:
Rs." + basicSalary + " | Total Salary: Rs." + calculateSalary());
}
public static void main(String[] args) {
Employee e1 = new Employee();
[Link] = 101; [Link] = "Alice"; [Link] = 30000;
Employee e2 = new Employee();
[Link] = 102; [Link] = "Bob"; [Link] = 45000;
[Link]();
[Link]();
}
}
Sample Output:
ID: 101 | Name: Alice | Basic: Rs.30000.0 | Total Salary: Rs.39000.0
ID: 102 | Name: Bob | Basic: Rs.45000.0 | Total Salary: Rs.58500.0
Program 21: Movie Ticket Booking
Java Code:
class MovieTicket {
String movieName;
int seatNumber;
double ticketPrice;
boolean booked = false;
void bookTicket() {
if (!booked) {
booked = true;
[Link]("Ticket booked for " + movieName + " | Seat: " +
seatNumber + " | Price: Rs." + ticketPrice);
} else {
[Link]("Seat " + seatNumber + " already booked.");
}
}
void cancelTicket() {
if (booked) {
booked = false;
[Link]("Ticket for " + movieName + " seat " + seatNumber +
" cancelled.");
} else {
[Link]("No booking found.");
}
}
void displayTicketDetails() {
[Link]("Movie: " + movieName + " | Seat: " + seatNumber + " |
Price: Rs." + ticketPrice + " | Status: " + (booked ? "Booked" : "Available"));
}
public static void main(String[] args) {
MovieTicket t1 = new MovieTicket();
[Link] = "Avengers"; [Link] = 15; [Link] = 250;
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Sample Output:
Movie: Avengers | Seat: 15 | Price: Rs.250.0 | Status: Available
Ticket booked for Avengers | Seat: 15 | Price: Rs.250.0
Seat 15 already booked.
Ticket for Avengers seat 15 cancelled.
Movie: Avengers | Seat: 15 | Price: Rs.250.0 | Status: Available
Program 22: Hospital Patient Record
Java Code:
class Patient {
int patientID;
String name;
String disease;
String doctorAssigned;
void assignDoctor(String doctor) {
doctorAssigned = doctor;
[Link]("Dr. " + doctorAssigned + " assigned to " + name);
}
void displayPatientDetails() {
[Link]("ID: " + patientID + " | Name: " + name + " | Disease: "
+ disease + " | Doctor: " + (doctorAssigned != null ? "Dr." + doctorAssigned : "Not
Assigned"));
}
public static void main(String[] args) {
Patient p1 = new Patient();
[Link] = 1; [Link] = "Alice"; [Link] = "Fever";
[Link]();
[Link]("Sharma");
[Link]();
}
}
Sample Output:
ID: 1 | Name: Alice | Disease: Fever | Doctor: Not Assigned
Dr. Sharma assigned to Alice
ID: 1 | Name: Alice | Disease: Fever | Doctor: [Link]
Program 23: Electricity Bill System (Classes & Objects)
Java Code:
class ElectricityBill {
int consumerNumber;
String consumerName;
int unitsConsumed;
double calculateBill() {
if (unitsConsumed <= 100) return unitsConsumed * 3;
else if (unitsConsumed <= 300) return 100 * 3 + (unitsConsumed - 100) * 5;
else return 100 * 3 + 200 * 5 + (unitsConsumed - 300) * 7;
}
void displayBill() {
[Link]("Consumer: " + consumerName + " | Units: " +
unitsConsumed + " | Bill: Rs." + calculateBill());
}
public static void main(String[] args) {
ElectricityBill eb1 = new ElectricityBill();
[Link] = 1001; [Link] = "Alice"; [Link] =
80;
ElectricityBill eb2 = new ElectricityBill();
[Link] = 1002; [Link] = "Bob"; [Link] =
250;
[Link]();
[Link]();
}
}
Sample Output:
Consumer: Alice | Units: 80 | Bill: Rs.240.0
Consumer: Bob | Units: 250 | Bill: Rs.1050.0
Program 24: Bank Account Initialization (Parameterized Constructor)
Java Code:
class BankAccountCons {
String accountNumber;
String accountHolderName;
double balance;
BankAccountCons(String accountNumber, String accountHolderName, double balance)
{
[Link] = accountNumber;
[Link] = accountHolderName;
[Link] = balance;
}
void displayDetails() {
[Link]("Account: " + accountNumber + " | Holder: " +
accountHolderName + " | Balance: Rs." + balance);
}
public static void main(String[] args) {
BankAccountCons a1 = new BankAccountCons("ACC001", "Alice", 10000);
BankAccountCons a2 = new BankAccountCons("ACC002", "Bob", 25000);
BankAccountCons a3 = new BankAccountCons("ACC003", "Charlie", 5000);
[Link]();
[Link]();
[Link]();
}
}
Sample Output:
Account: ACC001 | Holder: Alice | Balance: Rs.10000.0
Account: ACC002 | Holder: Bob | Balance: Rs.25000.0
Account: ACC003 | Holder: Charlie | Balance: Rs.5000.0
Program 25: Student Record System (Default Constructor)
Java Code:
class StudentRecord {
int rollNumber;
String name;
String department;
StudentRecord() {
rollNumber = 0;
name = "Unknown";
department = "Not Assigned";
}
void displayDetails() {
[Link]("Roll: " + rollNumber + " | Name: " + name + " |
Department: " + department);
}
public static void main(String[] args) {
StudentRecord s1 = new StudentRecord();
[Link]();
StudentRecord s2 = new StudentRecord();
[Link] = 101; [Link] = "Alice"; [Link] = "Computer Science";
[Link]();
}
}
Sample Output:
Roll: 0 | Name: Unknown | Department: Not Assigned
Roll: 101 | Name: Alice | Department: Computer Science
Program 26: Mobile Phone Store (Constructor)
Java Code:
class MobilePhoneStore {
String brand;
String model;
double price;
MobilePhoneStore(String brand, String model, double price) {
[Link] = brand;
[Link] = model;
[Link] = price;
}
void displayDetails() {
[Link]("Brand: " + brand + " | Model: " + model + " | Price:
Rs." + price);
}
public static void main(String[] args) {
MobilePhoneStore m1 = new MobilePhoneStore("Samsung", "Galaxy A54", 35000);
MobilePhoneStore m2 = new MobilePhoneStore("Apple", "iPhone 13", 69000);
MobilePhoneStore m3 = new MobilePhoneStore("OnePlus", "Nord CE3", 25000);
[Link]();
[Link]();
[Link]();
}
}
Sample Output:
Brand: Samsung | Model: Galaxy A54 | Price: Rs.35000.0
Brand: Apple | Model: iPhone 13 | Price: Rs.69000.0
Brand: OnePlus | Model: Nord CE3 | Price: Rs.25000.0
Program 27: Book Library System (Parameterized Constructor)
Java Code:
class BookLibrary {
int bookID;
String title;
String author;
BookLibrary(int bookID, String title, String author) {
[Link] = bookID;
[Link] = title;
[Link] = author;
}
void displayDetails() {
[Link]("ID: " + bookID + " | Title: " + title + " | Author: " +
author);
}
public static void main(String[] args) {
BookLibrary b1 = new BookLibrary(1, "Java Programming", "James Gosling");
BookLibrary b2 = new BookLibrary(2, "Data Structures", "Mark Allen");
BookLibrary b3 = new BookLibrary(3, "Operating Systems", "Tanenbaum");
BookLibrary b4 = new BookLibrary(4, "DBMS", "Ramakrishnan");
BookLibrary b5 = new BookLibrary(5, "Computer Networks", "Forouzan");
[Link](); [Link](); [Link]();
[Link](); [Link]();
}
}
Sample Output:
ID: 1 | Title: Java Programming | Author: James Gosling
ID: 2 | Title: Data Structures | Author: Mark Allen
ID: 3 | Title: Operating Systems | Author: Tanenbaum
ID: 4 | Title: DBMS | Author: Ramakrishnan
ID: 5 | Title: Computer Networks | Author: Forouzan
Program 28: Employee Salary Initialization (Constructor)
Java Code:
class EmployeeInit {
int employeeID;
String name;
double salary;
EmployeeInit(int employeeID, String name, double salary) {
[Link] = employeeID;
[Link] = name;
[Link] = salary;
}
void displayDetails() {
[Link]("ID: " + employeeID + " | Name: " + name + " | Salary:
Rs." + salary);
}
public static void main(String[] args) {
EmployeeInit e1 = new EmployeeInit(101, "Alice", 45000);
EmployeeInit e2 = new EmployeeInit(102, "Bob", 60000);
EmployeeInit e3 = new EmployeeInit(103, "Charlie", 35000);
[Link](); [Link](); [Link]();
}
}
Sample Output:
ID: 101 | Name: Alice | Salary: Rs.45000.0
ID: 102 | Name: Bob | Salary: Rs.60000.0
ID: 103 | Name: Charlie | Salary: Rs.35000.0
Program 29: Rectangle Area Calculator (Constructor)
Java Code:
class Rectangle {
double length;
double width;
Rectangle(double length, double width) {
[Link] = length;
[Link] = width;
}
double calculateArea() {
return length * width;
}
void displayArea() {
[Link]("Length: " + length + " | Width: " + width + " | Area: "
+ calculateArea());
}
public static void main(String[] args) {
Rectangle r1 = new Rectangle(10, 5);
Rectangle r2 = new Rectangle(7.5, 3.2);
[Link]();
[Link]();
}
}
Sample Output:
Length: 10.0 | Width: 5.0 | Area: 50.0
Length: 7.5 | Width: 3.2 | Area: 24.0
Program 30: Car Showroom System (Constructor)
Java Code:
class CarShowroom {
String carBrand;
String model;
double price;
CarShowroom(String carBrand, String model, double price) {
[Link] = carBrand;
[Link] = model;
[Link] = price;
}
void displayDetails() {
[Link]("Brand: " + carBrand + " | Model: " + model + " | Price:
Rs." + price);
}
public static void main(String[] args) {
CarShowroom c1 = new CarShowroom("Maruti", "Swift", 650000);
CarShowroom c2 = new CarShowroom("Hyundai", "Creta", 1200000);
CarShowroom c3 = new CarShowroom("Tata", "Nexon", 850000);
[Link](); [Link](); [Link]();
}
}
Sample Output:
Brand: Maruti | Model: Swift | Price: Rs.650000.0
Brand: Hyundai | Model: Creta | Price: Rs.1200000.0
Brand: Tata | Model: Nexon | Price: Rs.850000.0
Program 31: Electricity Bill System (Constructor)
Java Code:
class ElectricityBillCons {
String consumerName;
int unitsConsumed;
ElectricityBillCons(String consumerName, int unitsConsumed) {
[Link] = consumerName;
[Link] = unitsConsumed;
}
double calculateBill() {
if (unitsConsumed <= 100) return unitsConsumed * 3;
else if (unitsConsumed <= 300) return 300 + (unitsConsumed - 100) * 5;
else return 1300 + (unitsConsumed - 300) * 7;
}
void displayBill() {
[Link]("Consumer: " + consumerName + " | Units: " +
unitsConsumed + " | Bill: Rs." + calculateBill());
}
public static void main(String[] args) {
ElectricityBillCons e1 = new ElectricityBillCons("Alice", 90);
ElectricityBillCons e2 = new ElectricityBillCons("Bob", 200);
[Link](); [Link]();
}
}
Sample Output:
Consumer: Alice | Units: 90 | Bill: Rs.270.0
Consumer: Bob | Units: 200 | Bill: Rs.800.0
Program 32: Movie Ticket Booking (Constructor)
Java Code:
class MovieTicketCons {
String movieName;
int seatNumber;
double ticketPrice;
MovieTicketCons(String movieName, int seatNumber, double ticketPrice) {
[Link] = movieName;
[Link] = seatNumber;
[Link] = ticketPrice;
}
void displayTicketDetails() {
[Link]("Movie: " + movieName + " | Seat: " + seatNumber + " |
Price: Rs." + ticketPrice);
}
public static void main(String[] args) {
MovieTicketCons t1 = new MovieTicketCons("Avatar", 12, 300);
MovieTicketCons t2 = new MovieTicketCons("Interstellar", 7, 250);
MovieTicketCons t3 = new MovieTicketCons("Inception", 20, 350);
[Link](); [Link]();
[Link]();
}
}
Sample Output:
Movie: Avatar | Seat: 12 | Price: Rs.300.0
Movie: Interstellar | Seat: 7 | Price: Rs.250.0
Movie: Inception | Seat: 20 | Price: Rs.350.0
Program 33: Product Inventory System (Constructor)
Java Code:
class ProductInventory {
int productID;
String productName;
double price;
ProductInventory(int productID, String productName, double price) {
[Link] = productID;
[Link] = productName;
[Link] = price;
}
void displayDetails() {
[Link]("ID: " + productID + " | Product: " + productName + " |
Price: Rs." + price);
}
public static void main(String[] args) {
ProductInventory p1 = new ProductInventory(1, "Laptop", 55000);
ProductInventory p2 = new ProductInventory(2, "Mouse", 800);
ProductInventory p3 = new ProductInventory(3, "Keyboard", 1500);
[Link](); [Link](); [Link]();
}
}
Sample Output:
ID: 1 | Product: Laptop | Price: Rs.55000.0
ID: 2 | Product: Mouse | Price: Rs.800.0
ID: 3 | Product: Keyboard | Price: Rs.1500.0
Program 34: Calculator Using Static Methods
Java Code:
class StaticCalculator {
static int add(int a, int b) { return a + b; }
static int subtract(int a, int b) { return a - b; }
static int multiply(int a, int b) { return a * b; }
static double divide(int a, int b) {
if (b == 0) { [Link]("Cannot divide by zero!"); return 0; }
return (double) a / b;
}
public static void main(String[] args) {
[Link]("10 + 5 = " + [Link](10, 5));
[Link]("10 - 5 = " + [Link](10, 5));
[Link]("10 * 5 = " + [Link](10, 5));
[Link]("10 / 5 = " + [Link](10, 5));
[Link](10, 0);
}
}
Sample Output:
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
10 / 5 = 2.0
Cannot divide by zero!
Program 35: Temperature Conversion: Celsius to Fahrenheit
Java Code:
class TemperatureConverter {
static double celsiusToFahrenheit(double celsius) {
return (celsius * 9 / 5) + 32;
}
public static void main(String[] args) {
double[] temps = {0, 25, 37, 100};
for (double t : temps) {
[Link](t + "C = " + celsiusToFahrenheit(t) + "F");
}
}
}
Sample Output:
0.0C = 32.0F
25.0C = 77.0F
37.0C = 98.6F
100.0C = 212.0F
Program 36: Area of Circle Using Static Method
Java Code:
class CircleArea {
static double calculateArea(double radius) {
return 3.14 * radius * radius;
}
public static void main(String[] args) {
[Link]("Area with radius 5 : " + [Link](5));
[Link]("Area with radius 7.5: " +
[Link](7.5));
[Link]("Area with radius 10 : " +
[Link](10));
}
}
Sample Output:
Area with radius 5 : 78.5
Area with radius 7.5: 176.625
Area with radius 10 : 314.0
Program 37: Student Registration Counter (Static Variable)
Java Code:
class StudentRegistration {
static int studentCount = 0;
String name;
StudentRegistration(String name) {
[Link] = name;
studentCount++;
[Link](name + " registered. Total Students: " + studentCount);
}
public static void main(String[] args) {
new StudentRegistration("Alice");
new StudentRegistration("Bob");
new StudentRegistration("Charlie");
new StudentRegistration("Diana");
[Link]("Total Registered Students: " +
[Link]);
}
}
Sample Output:
Alice registered. Total Students: 1
Bob registered. Total Students: 2
Charlie registered. Total Students: 3
Diana registered. Total Students: 4
Total Registered Students: 4
Program 38: Factorial Using Static Method
Java Code:
class FactorialCalc {
static long factorial(int n) {
long result = 1;
for (int i = 2; i <= n; i++) result *= i;
return result;
}
public static void main(String[] args) {
[Link]("Factorial of 0 : " + [Link](0));
[Link]("Factorial of 5 : " + [Link](5));
[Link]("Factorial of 10: " + [Link](10));
}
}
Sample Output:
Factorial of 0 : 1
Factorial of 5 : 120
Factorial of 10: 3628800
Program 39: Prime Numbers up to 100 Using Static Method
Java Code:
class PrimeNumbers {
static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i <= [Link](n); i++)
if (n % i == 0) return false;
return true;
}
static void displayPrimes(int limit) {
[Link]("Primes up to " + limit + ": ");
for (int i = 2; i <= limit; i++)
if (isPrime(i)) [Link](i + " ");
[Link]();
}
public static void main(String[] args) {
[Link](100);
}
}
Sample Output:
Primes up to 100: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83
89 97
Program 40: Reverse a Number Using Static Method
Java Code:
class ReverseNumber {
static int reverse(int n) {
int reversed = 0;
boolean neg = n < 0;
n = [Link](n);
while (n != 0) { reversed = reversed * 10 + n % 10; n /= 10; }
return neg ? -reversed : reversed;
}
public static void main(String[] args) {
[Link]("Reverse of 12345: " + [Link](12345));
[Link]("Reverse of 9800 : " + [Link](9800));
[Link]("Reverse of -4567: " + [Link](-4567));
}
}
Sample Output:
Reverse of 12345: 54321
Reverse of 9800 : 89
Reverse of -4567: -7654
Program 41: Reverse a String
Java Code:
import [Link];
class ReverseString {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
String reversed = new StringBuilder(str).reverse().toString();
[Link]("Reversed String: " + reversed);
}
}
Sample Input:
Enter a string: Hello World
Sample Output:
Reversed String: dlroW olleH
Program 42: Palindrome Check (String)
Java Code:
import [Link];
class PalindromeString {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
String reversed = new StringBuilder(str).reverse().toString();
if ([Link](reversed))
[Link](str + " is a Palindrome.");
else
[Link](str + " is not a Palindrome.");
}
}
Sample Input:
Enter a string: madam
Sample Output:
madam is a Palindrome.
Program 43: Count Vowels in a String
Java Code:
import [Link];
class CountVowels {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]().toLowerCase();
int count = 0;
for (int i = 0; i < [Link](); i++) {
char c = [Link](i);
if (c=='a'||c=='e'||c=='i'||c=='o'||c=='u') count++;
}
[Link]("Number of vowels: " + count);
}
}
Sample Input:
Enter a string: Hello World
Sample Output:
Number of vowels: 3
Program 44: Convert String to Uppercase
Java Code:
import [Link];
class ToUpperCase {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
[Link]("Uppercase: " + [Link]());
}
}
Sample Input:
Enter a string: hello world
Sample Output:
Uppercase: HELLO WORLD
Program 45: Convert String to Lowercase
Java Code:
import [Link];
class ToLowerCase {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
[Link]("Lowercase: " + [Link]());
}
}
Sample Input:
Enter a string: HELLO WORLD
Sample Output:
Lowercase: hello world
Program 46: Remove All Spaces from String
Java Code:
import [Link];
class RemoveSpaces {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
String result = [Link](" ", "");
[Link]("String without spaces: " + result);
}
}
Sample Input:
Enter a string: Hello World Java
Sample Output:
String without spaces: HelloWorldJava
Program 47: Replace Character in String
Java Code:
import [Link];
class ReplaceChar {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
[Link]("Enter character to replace: ");
char oldChar = [Link]().charAt(0);
[Link]("Enter new character: ");
char newChar = [Link]().charAt(0);
[Link]("Result: " + [Link](oldChar, newChar));
}
}
Sample Input:
Enter a string: programming
Enter character to replace: g
Enter new character: x
Sample Output:
Result: proxxramminx
Program 48: Employee Class with Parameterized Constructor
Java Code:
class Employee {
int empId;
String empName;
double salary;
Employee(int empId, String empName, double salary) {
[Link] = empId;
[Link] = empName;
[Link] = salary;
}
void display() {
[Link]("Employee ID : " + empId);
[Link]("Employee Name: " + empName);
[Link]("Salary : Rs." + salary);
}
public static void main(String[] args) {
Employee e1 = new Employee(101, "Alice", 55000);
Employee e2 = new Employee(102, "Bob", 72000);
[Link]();
[Link]("---");
[Link]();
}
}
Sample Output:
Employee ID : 101
Employee Name: Alice
Salary : Rs.55000.0
---
Employee ID : 102
Employee Name: Bob
Salary : Rs.72000.0
Program 49: Constructor Overloading – Rectangle Area
Java Code:
class Rectangle {
double length, width;
Rectangle(double side) { length = side; width = side; }
Rectangle(double length, double width) { [Link] = length; [Link] =
width; }
double area() { return length * width; }
public static void main(String[] args) {
Rectangle r1 = new Rectangle(5);
Rectangle r2 = new Rectangle(4, 7);
[Link]("Square Area (side=5): " + [Link]());
[Link]("Rectangle Area (4x7): " + [Link]());
}
}
Sample Output:
Square Area (side=5): 25.0
Rectangle Area (4x7): 28.0
Program 50: Car Class with Constructor
Java Code:
class Car {
String brand, model;
double price;
Car(String brand, String model, double price) {
[Link] = brand; [Link] = model; [Link] = price;
}
void display() {
[Link]("Brand: " + brand + " | Model: " + model + " | Price:
Rs." + price);
}
public static void main(String[] args) {
Car c1 = new Car("Maruti", "Swift", 650000);
Car c2 = new Car("Honda", "City", 1100000);
[Link](); [Link]();
}
}
Sample Output:
Brand: Maruti | Model: Swift | Price: Rs.650000.0
Brand: Honda | Model: City | Price: Rs.1100000.0
Program 51: BankAccount with Constructor
Java Code:
class BankAccount {
String accountNumber, accountHolderName;
double balance;
BankAccount(String accountNumber, String accountHolderName, double balance) {
[Link] = accountNumber;
[Link] = accountHolderName;
[Link] = balance;
}
void display() {
[Link]("Account No : " + accountNumber);
[Link]("Holder Name : " + accountHolderName);
[Link]("Balance : Rs." + balance);
}
public static void main(String[] args) {
BankAccount a1 = new BankAccount("ACC001", "Alice", 25000);
BankAccount a2 = new BankAccount("ACC002", "Bob", 50000);
[Link](); [Link]("---"); [Link]();
}
}
Sample Output:
Account No : ACC001
Holder Name : Alice
Balance : Rs.25000.0
---
Account No : ACC002
Holder Name : Bob
Balance : Rs.50000.0
Program 52: Factorial Using Constructor
Java Code:
class FactorialConstructor {
long result;
FactorialConstructor(int n) {
result = 1;
for (int i = 2; i <= n; i++) result *= i;
[Link]("Factorial of " + n + " = " + result);
}
public static void main(String[] args) {
new FactorialConstructor(5);
new FactorialConstructor(10);
new FactorialConstructor(0);
}
}
Sample Output:
Factorial of 5 = 120
Factorial of 10 = 3628800
Factorial of 0 = 1
Program 53: ComplexNumber Addition Using Constructor
Java Code:
class ComplexNumber {
double real, imag;
ComplexNumber(double real, double imag) { [Link] = real; [Link] = imag; }
ComplexNumber add(ComplexNumber other) {
return new ComplexNumber([Link] + [Link], [Link] + [Link]);
}
void display() { [Link](real + " + " + imag + "i"); }
public static void main(String[] args) {
ComplexNumber c1 = new ComplexNumber(3, 4);
ComplexNumber c2 = new ComplexNumber(1, 2);
[Link]("C1 = "); [Link]();
[Link]("C2 = "); [Link]();
[Link]("Sum = "); [Link](c2).display();
}
}
Sample Output:
C1 = 3.0 + 4.0i
C2 = 1.0 + 2.0i
Sum = 4.0 + 6.0i
Program 54: Circle – Area and Circumference Using Constructor
Java Code:
class Circle {
double radius;
Circle(double radius) {
[Link] = radius;
double area = 3.14 * radius * radius;
double circumference = 2 * 3.14 * radius;
[Link]("Radius : " + radius);
[Link]("Area : %.2f%n", area);
[Link]("Circumference: %.2f%n", circumference);
}
public static void main(String[] args) {
new Circle(5);
[Link]("---");
new Circle(7.5);
}
}
Sample Output:
Radius : 5.0
Area : 78.50
Circumference: 31.40
---
Radius : 7.5
Area : 176.63
Circumference: 47.10
Program 55: Box – Volume Using Constructor
Java Code:
class Box {
double length, width, height;
Box(double side) { length = width = height = side; }
Box(double length, double width, double height) {
[Link] = length; [Link] = width; [Link] = height;
}
double volume() { return length * width * height; }
public static void main(String[] args) {
Box b1 = new Box(4);
Box b2 = new Box(3, 5, 7);
[Link]("Cube Volume (side=4): " + [Link]());
[Link]("Box Volume (3x5x7) : " + [Link]());
}
}
Sample Output:
Cube Volume (side=4): 64.0
Box Volume (3x5x7) : 105.0
Program 60: Simple and Compound Interest
Java Code:
import [Link];
class Interest {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter Principal: ");
double p = [Link]();
[Link]("Enter Rate (%): ");
double r = [Link]();
[Link]("Enter Time (years): ");
int t = [Link]();
double si = (p * r * t) / 100;
double ci = p * [Link](1 + r / 100, t) - p;
[Link]("Simple Interest : Rs.%.2f%n", si);
[Link]("Compound Interest: Rs.%.2f%n", ci);
}
}
Sample Input:
Enter Principal: 10000
Enter Rate (%): 10
Enter Time (years): 2
Sample Output:
Simple Interest : Rs.2000.00
Compound Interest: Rs.2100.00
Program 61: Volume and Surface Area of Cylinder
Java Code:
class Cylinder {
double radius, height;
Cylinder(double radius, double height) { [Link] = radius; [Link] =
height; }
double volume() { return 3.14 * radius * radius * height; }
double surfaceArea() { return 2 * 3.14 * radius * (radius + height); }
void display() {
[Link]("Volume : " + volume());
[Link]("Surface Area: " + surfaceArea());
}
public static void main(String[] args) { new Cylinder(5, 10).display(); }
}
Sample Output:
Volume : 785.0
Surface Area: 471.0
Program 62: Euclidean Distance Between Two Points
Java Code:
import [Link];
class EuclideanDistance {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter x1 y1: ");
double x1 = [Link](), y1 = [Link]();
[Link]("Enter x2 y2: ");
double x2 = [Link](), y2 = [Link]();
double dist = [Link]([Link](x2-x1,2) + [Link](y2-y1,2));
[Link]("Euclidean Distance: %.2f%n", dist);
}
}
Sample Input:
Enter x1 y1: 1 2
Enter x2 y2: 4 6
Sample Output:
Euclidean Distance: 5.00
Program 63: Volume and Surface Area of Box Using Constructor
Java Code:
class BoxSurface {
double l, w, h;
BoxSurface(double l, double w, double h) { this.l=l; this.w=w; this.h=h; }
double volume() { return l * w * h; }
double surfaceArea() { return 2 * (l*w + w*h + h*l); }
void display() {
[Link]("Volume : " + volume());
[Link]("Surface Area: " + surfaceArea());
}
public static void main(String[] args) { new BoxSurface(3, 4, 5).display(); }
}
Sample Output:
Volume : 60.0
Surface Area: 94.0
Program 64: Triangle Validity and Type
Java Code:
import [Link];
class TriangleType {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter three sides: ");
double a = [Link](), b = [Link](), c = [Link]();
if (a+b>c && b+c>a && a+c>b) {
[Link]("Valid Triangle.");
if (a==b && b==c) [Link]("Type: Equilateral");
else if (a==b || b==c || a==c) [Link]("Type: Isosceles");
else [Link]("Type: Scalene");
} else {
[Link]("Not a Valid Triangle.");
}
}
}
Sample Input:
Enter three sides: 5 5 8
Sample Output:
Valid Triangle.
Type: Isosceles
Program 65: Volume of Sphere Using Constructor
Java Code:
class Sphere {
double radius;
Sphere(double radius) { [Link] = radius; }
double volume() { return (4.0/3) * 3.14 * radius * radius * radius; }
void display() {
[Link]("Radius: " + radius);
[Link]("Volume: %.2f%n", volume());
}
public static void main(String[] args) { new Sphere(6).display(); }
}
Sample Output:
Radius: 6.0
Volume: 904.32
Program 66: Menu-Driven Calculator
Java Code:
import [Link];
class MenuCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter two numbers: ");
double a = [Link](), b = [Link]();
[Link]("1. Addition\n2. Subtraction\n3. Multiplication\n4.
Division");
[Link]("Enter choice: ");
int choice = [Link]();
switch (choice) {
case 1: [Link]("Result: " + (a + b)); break;
case 2: [Link]("Result: " + (a - b)); break;
case 3: [Link]("Result: " + (a * b)); break;
case 4:
if (b != 0) [Link]("Result: " + (a / b));
else [Link]("Division by zero not allowed.");
break;
default: [Link]("Invalid choice.");
}
}
}
Sample Input:
Enter two numbers: 20 4
Enter choice: 4
Sample Output:
1. Addition
2. Subtraction
3. Multiplication
4. Division
Result: 5.0
Program 67: Area and Perimeter of Triangle Using Constructor
Java Code:
class Triangle {
double a, b, c;
Triangle(double a, double b, double c) { this.a=a; this.b=b; this.c=c; }
double perimeter() { return a + b + c; }
double area() { double s=perimeter()/2; return [Link](s*(s-a)*(s-b)*(s-c));
}
void display() {
[Link]("Perimeter: %.2f%n", perimeter());
[Link]("Area : %.2f%n", area());
}
public static void main(String[] args) { new Triangle(3, 4, 5).display(); }
}
Sample Output:
Perimeter: 12.00
Area : 6.00
Program 68: Fibonacci Series – First N Terms
Java Code:
import [Link];
class Fibonacci {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of terms: ");
int n = [Link]();
int a = 0, b = 1;
[Link]("Fibonacci: ");
for (int i = 0; i < n; i++) {
[Link](a + " ");
int temp = a + b; a = b; b = temp;
}
[Link]();
}
}
Sample Input:
Enter number of terms: 8
Sample Output:
Fibonacci: 0 1 1 2 3 5 8 13
Program 69: Prime Number Check
Java Code:
import [Link];
class PrimeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int n = [Link]();
boolean prime = n >= 2;
for (int i = 2; i <= [Link](n); i++)
if (n % i == 0) { prime = false; break; }
[Link](n + (prime ? " is a Prime number." : " is not a Prime
number."));
}
}
Sample Input:
Enter a number: 17
Sample Output:
17 is a Prime number.
Program 70: Sum of Cosine Series
Java Code:
import [Link];
class CosineSeries {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter angle in degrees: ");
double deg = [Link]();
[Link]("Enter number of terms: ");
int n = [Link]();
double x = [Link](deg);
double sum = 0, term = 1;
int sign = 1;
for (int i = 0; i < n; i++) {
if (i == 0) { sum += term; continue; }
sign *= -1;
term = term * x * x / ((2*i-1) * (2*i));
sum += sign * term;
}
[Link]("cos(%.1f) using series = %.4f%n", deg, sum);
[Link]("[Link](%.1f) = %.4f%n", deg, [Link](x));
}
}
Sample Input:
Enter angle in degrees: 60
Enter number of terms: 5
Sample Output:
cos(60.0) using series = 0.5000
[Link](60.0) = 0.5000
Program 71: Area and Perimeter of Rectangle Using Constructor
Java Code:
class RectangleAP {
double length, width;
RectangleAP(double length, double width) { [Link]=length;
[Link]=width; }
double area() { return length * width; }
double perimeter() { return 2 * (length + width); }
void display() {
[Link]("Length : " + length);
[Link]("Width : " + width);
[Link]("Area : " + area());
[Link]("Perimeter: " + perimeter());
}
public static void main(String[] args) { new RectangleAP(8, 5).display(); }
}
Sample Output:
Length : 8.0
Width : 5.0
Area : 40.0
Perimeter: 26.0
Program 72: Rotate Array Elements Clockwise by 2 Positions
Java Code:
import [Link];
class RotateArray {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of elements: ");
int n = [Link]();
int[] arr = new int[n];
[Link]("Enter elements: ");
for (int i = 0; i < n; i++) arr[i] = [Link]();
[Link]("Original: ");
for (int x : arr) [Link](x + " ");
for (int r = 0; r < 2; r++) {
int last = arr[n-1];
for (int i = n-1; i > 0; i--) arr[i] = arr[i-1];
arr[0] = last;
}
[Link]("\nRotated : ");
for (int x : arr) [Link](x + " ");
[Link]();
}
}
Sample Input:
Enter number of elements: 6
Enter elements: 1 2 3 4 5 6
Sample Output:
Original: 1 2 3 4 5 6
Rotated : 5 6 1 2 3 4
Program 73: Volume of Cone Using Constructor
Java Code:
class Cone {
double radius, height;
Cone(double radius, double height) { [Link]=radius; [Link]=height; }
double volume() { return (1.0/3) * 3.14 * radius * radius * height; }
void display() {
[Link]("Radius: " + radius + " | Height: " + height);
[Link]("Volume: %.2f%n", volume());
}
public static void main(String[] args) { new Cone(5, 12).display(); }
}
Sample Output:
Radius: 5.0 | Height: 12.0
Volume: 314.00
Program 74: Arrange N Integers in Descending Order
Java Code:
import [Link];
import [Link];
import [Link];
class DescendingOrder {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of elements: ");
int n = [Link]();
Integer[] arr = new Integer[n];
[Link]("Enter elements: ");
for (int i = 0; i < n; i++) arr[i] = [Link]();
[Link](arr, [Link]());
[Link]("Descending order: ");
for (int x : arr) [Link](x + " ");
[Link]();
}
}
Sample Input:
Enter number of elements: 5
Enter elements: 40 10 30 20 50
Sample Output:
Descending order: 50 40 30 20 10
Program 75: Store and Display Employee Information
Java Code:
import [Link];
class EmployeeInfo {
String name; int empCode; double salary;
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of employees: ");
int n = [Link]();
EmployeeInfo[] emp = new EmployeeInfo[n];
for (int i = 0; i < n; i++) {
emp[i] = new EmployeeInfo();
[Link]("Name: "); emp[i].name = [Link]();
[Link]("Code: "); emp[i].empCode = [Link]();
[Link]("Salary: "); emp[i].salary = [Link]();
}
[Link]("\n--- Employee Details ---");
for (EmployeeInfo e : emp)
[Link]("Name: " + [Link] + " | Code: " + [Link] + " |
Salary: Rs." + [Link]);
}
}
Sample Input:
Enter number of employees: 2
Name: Alice Code: 101 Salary: 45000
Name: Bob Code: 102 Salary: 60000
Sample Output:
--- Employee Details ---
Name: Alice | Code: 101 | Salary: Rs.45000.0
Name: Bob | Code: 102 | Salary: Rs.60000.0
Program 76: Mean, Variance and Standard Deviation
Java Code:
import [Link];
class Statistics {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of elements: ");
int n = [Link]();
double[] arr = new double[n];
[Link]("Enter elements: ");
double sum = 0;
for (int i = 0; i < n; i++) { arr[i] = [Link](); sum += arr[i]; }
double mean = sum / n;
double varSum = 0;
for (double x : arr) varSum += (x - mean) * (x - mean);
double variance = varSum / n;
[Link]("Mean : %.2f%n", mean);
[Link]("Variance : %.2f%n", variance);
[Link]("Standard Deviation: %.2f%n", [Link](variance));
}
}
Sample Input:
Enter number of elements: 5
Enter elements: 10 20 30 40 50
Sample Output:
Mean : 30.00
Variance : 200.00
Standard Deviation: 14.14
Program 77: Store and Display Book Information
Java Code:
import [Link];
class BookInfo {
String name; int pages; double price;
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of books: ");
int n = [Link](); [Link]();
BookInfo[] books = new BookInfo[n];
for (int i = 0; i < n; i++) {
books[i] = new BookInfo();
[Link]("Book Name: "); books[i].name = [Link]();
[Link]("Pages: "); books[i].pages = [Link]();
[Link]("Price: "); books[i].price = [Link]();
[Link]();
}
[Link]("\n--- Book Details ---");
for (BookInfo b : books)
[Link]("Name: " + [Link] + " | Pages: " + [Link] + " |
Price: Rs." + [Link]);
}
}
Sample Input:
Enter number of books: 2
Book Name: Java Basics Pages: 350 Price: 450
Book Name: Data Structures Pages: 500 Price: 600
Sample Output:
--- Book Details ---
Name: Java Basics | Pages: 350 | Price: Rs.450.0
Name: Data Structures | Pages: 500 | Price: Rs.600.0
Program 78: Check if Matrix is Symmetric
Java Code:
import [Link];
class SymmetricMatrix {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter matrix size n: ");
int n = [Link]();
int[][] mat = new int[n][n];
[Link]("Enter matrix:");
for (int i=0;i<n;i++) for (int j=0;j<n;j++) mat[i][j]=[Link]();
boolean sym = true;
for (int i=0;i<n&&sym;i++) for (int j=0;j<n&&sym;j++) if
(mat[i][j]!=mat[j][i]) sym=false;
[Link]("Matrix is " + (sym ? "" : "NOT ") + "Symmetric.");
}
}
Sample Input:
Enter matrix size n: 3
Enter matrix:
1 2 3
2 4 5
3 5 6
Sample Output:
Matrix is Symmetric.
Program 79: Transpose of a Square Matrix
Java Code:
import [Link];
class TransposeMatrix {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter size n: ");
int n = [Link]();
int[][] mat = new int[n][n];
[Link]("Enter matrix:");
for (int i=0;i<n;i++) for (int j=0;j<n;j++) mat[i][j]=[Link]();
for (int i=0;i<n;i++)
for (int j=i+1;j<n;j++) { int t=mat[i][j]; mat[i][j]=mat[j][i];
mat[j][i]=t; }
[Link]("Transpose:");
for (int[] row : mat) { for (int x : row) [Link](x+" ");
[Link](); }
}
}
Sample Input:
Enter size n: 3
Enter matrix:
1 2 3
4 5 6
7 8 9
Sample Output:
Transpose:
1 4 7
2 5 8
3 6 9
Program 80: Armstrong Number Check (3-digit)
Java Code:
import [Link];
class ArmstrongCheck {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a 3-digit number: ");
int n = [Link](), temp = n, sum = 0;
while (temp != 0) { int d = temp % 10; sum += d*d*d; temp /= 10; }
[Link](n + (sum == n ? " is an Armstrong number." : " is NOT an
Armstrong number."));
}
}
Sample Input:
Enter a 3-digit number: 153
Sample Output:
153 is an Armstrong number.
Program 81: Add Two Complex Numbers
Java Code:
class ComplexAdd {
double real, imag;
ComplexAdd(double real, double imag) { [Link]=real; [Link]=imag; }
ComplexAdd add(ComplexAdd o) { return new ComplexAdd(real+[Link], imag+[Link]);
}
void display() { [Link](real + " + " + imag + "i"); }
public static void main(String[] args) {
ComplexAdd c1 = new ComplexAdd(4, 3);
ComplexAdd c2 = new ComplexAdd(2, 5);
[Link]("C1 = "); [Link]();
[Link]("C2 = "); [Link]();
[Link]("Sum = "); [Link](c2).display();
}
}
Sample Output:
C1 = 4.0 + 3.0i
C2 = 2.0 + 5.0i
Sum = 6.0 + 8.0i
Program 82: Palindrome Check (Integer)
Java Code:
import [Link];
class PalindromeInt {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int n = [Link](), orig = n, rev = 0;
while (n != 0) { rev = rev * 10 + n % 10; n /= 10; }
[Link](orig + (orig == rev ? " is a Palindrome." : " is not a
Palindrome."));
}
}
Sample Input:
Enter a number: 1221
Sample Output:
1221 is a Palindrome.
Program 83: Add Two Distances (Feet and Inches)
Java Code:
class Distance {
int feet, inches;
Distance(int feet, int inches) { [Link]=feet; [Link]=inches; }
Distance add(Distance d) {
int totalIn = [Link] + [Link];
int totalFt = [Link] + [Link] + totalIn / 12;
return new Distance(totalFt, totalIn % 12);
}
void display() { [Link](feet + " feet " + inches + " inches"); }
public static void main(String[] args) {
Distance d1 = new Distance(5, 10);
Distance d2 = new Distance(3, 7);
[Link]("D1 = "); [Link]();
[Link]("D2 = "); [Link]();
[Link]("Sum = "); [Link](d2).display();
}
}
Sample Output:
D1 = 5 feet 10 inches
D2 = 3 feet 7 inches
Sum = 9 feet 5 inches
Program 84: GCD of Two Numbers
Java Code:
import [Link];
class GCD {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter two numbers: ");
int a = [Link](), b = [Link]();
while (b != 0) { int t = b; b = a % b; a = t; }
[Link]("GCD = " + a);
}
}
Sample Input:
Enter two numbers: 48 18
Sample Output:
GCD = 6
Program 85: nCr Calculation
Java Code:
import [Link];
class NCR {
static long factorial(int n) {
long f = 1;
for (int i = 2; i <= n; i++) f *= i;
return f;
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter n and r: ");
int n = [Link](), r = [Link]();
if (r > n) { [Link]("r cannot be greater than n."); return; }
long ncr = factorial(n) / (factorial(r) * factorial(n-r));
[Link]("nCr (" + n + "C" + r + ") = " + ncr);
}
}
Sample Input:
Enter n and r: 6 2
Sample Output:
nCr (6C2) = 15
Program 86: Volume of Sphere Using Constructor (II)
Java Code:
class SphereVol {
double radius;
SphereVol(double radius) { [Link] = radius; }
double volume() { return (4.0/3) * 3.14 * radius * radius * radius; }
public static void main(String[] args) {
SphereVol s1 = new SphereVol(4);
SphereVol s2 = new SphereVol(7);
[Link]("Volume (r=4): %.2f%n", [Link]());
[Link]("Volume (r=7): %.2f%n", [Link]());
}
}
Sample Output:
Volume (r=4): 267.95
Volume (r=7): 1436.03
Program 87: Search Integer in Array and Find Frequency
Java Code:
import [Link];
class SearchFrequency {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of elements: ");
int n = [Link]();
int[] arr = new int[n];
[Link]("Enter elements: ");
for (int i = 0; i < n; i++) arr[i] = [Link]();
[Link]("Enter number to search: ");
int key = [Link](), freq = 0;
for (int x : arr) if (x == key) freq++;
if (freq > 0) [Link](key + " found with frequency: " + freq);
else [Link](key + " not found in array.");
}
}
Sample Input:
Enter number of elements: 7
Enter elements: 4 2 4 7 4 1 4
Enter number to search: 4
Sample Output:
4 found with frequency: 4
Program 88: Sum of All Elements of a Matrix
Java Code:
import [Link];
class MatrixSum {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter rows and columns: ");
int r = [Link](), c = [Link]();
int sum = 0;
[Link]("Enter matrix:");
for (int i=0;i<r;i++) for (int j=0;j<c;j++) sum += [Link]();
[Link]("Sum of all elements: " + sum);
}
}
Sample Input:
Enter rows and columns: 3 3
Enter matrix:
1 2 3
4 5 6
7 8 9
Sample Output:
Sum of all elements: 45
Program 89: Sum of Diagonal Elements of a Matrix
Java Code:
import [Link];
class DiagonalSum {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter size n of square matrix: ");
int n = [Link]();
int[][] mat = new int[n][n];
[Link]("Enter matrix:");
for (int i=0;i<n;i++) for (int j=0;j<n;j++) mat[i][j]=[Link]();
int sum = 0;
for (int i = 0; i < n; i++) sum += mat[i][i];
[Link]("Sum of diagonal elements: " + sum);
}
}
Sample Input:
Enter size n of square matrix: 3
Enter matrix:
1 2 3
4 5 6
7 8 9
Sample Output:
Sum of diagonal elements: 15
Program 90: Store and Display Badminton Player Information
Java Code:
import [Link];
class BadmintonPlayer {
String name; int matchesPlayed, gamesWon;
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of players: ");
int n = [Link](); [Link]();
BadmintonPlayer[] players = new BadmintonPlayer[n];
for (int i = 0; i < n; i++) {
players[i] = new BadmintonPlayer();
[Link]("Name: "); players[i].name = [Link]();
[Link]("Matches Played: "); players[i].matchesPlayed =
[Link]();
[Link]("Games Won: "); players[i].gamesWon = [Link]();
[Link]();
}
[Link]("\n--- Player Details ---");
for (BadmintonPlayer p : players)
[Link]("Name: " + [Link] + " | Matches: " + [Link]
+ " | Won: " + [Link]);
}
}
Sample Input:
Enter number of players: 2
Name: Sindhu Matches Played: 30 Games Won: 22
Name: Saina Matches Played: 25 Games Won: 18
Sample Output:
--- Player Details ---
Name: Sindhu | Matches: 30 | Won: 22
Name: Saina | Matches: 25 | Won: 18
Program 91: Sum of Boundary Elements of a Matrix
Java Code:
import [Link];
class BoundarySum {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter rows and columns: ");
int r = [Link](), c = [Link]();
int[][] mat = new int[r][c];
[Link]("Enter matrix:");
for (int i=0;i<r;i++) for (int j=0;j<c;j++) mat[i][j]=[Link]();
int sum = 0;
for (int i=0;i<r;i++)
for (int j=0;j<c;j++)
if (i==0||i==r-1||j==0||j==c-1) sum += mat[i][j];
[Link]("Sum of boundary elements: " + sum);
}
}
Sample Input:
Enter rows and columns: 3 3
Enter matrix:
1 2 3
4 5 6
7 8 9
Sample Output:
Sum of boundary elements: 40
Program 92: Addition and Subtraction of Two Matrices
Java Code:
import [Link];
class MatrixAddSub {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter rows and columns: ");
int r = [Link](), c = [Link]();
int[][] a = new int[r][c], b = new int[r][c];
[Link]("Enter Matrix A:");
for (int i=0;i<r;i++) for (int j=0;j<c;j++) a[i][j]=[Link]();
[Link]("Enter Matrix B:");
for (int i=0;i<r;i++) for (int j=0;j<c;j++) b[i][j]=[Link]();
[Link]("Addition:");
for (int i=0;i<r;i++) { for (int j=0;j<c;j++)
[Link]((a[i][j]+b[i][j])+" "); [Link](); }
[Link]("Subtraction:");
for (int i=0;i<r;i++) { for (int j=0;j<c;j++) [Link]((a[i][j]-
b[i][j])+" "); [Link](); }
}
}
Sample Input:
Enter rows and columns: 2 2
Enter Matrix A: 1 2 3 4
Enter Matrix B: 5 6 7 8
Sample Output:
Addition:
6 8
10 12
Subtraction:
-4 -4
-4 -4
Program 93: Median of N Integers
Java Code:
import [Link];
import [Link];
class Median {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of elements: ");
int n = [Link]();
double[] arr = new double[n];
[Link]("Enter elements: ");
for (int i = 0; i < n; i++) arr[i] = [Link]();
[Link](arr);
double median = (n % 2 == 0) ? (arr[n/2-1] + arr[n/2]) / 2.0 : arr[n/2];
[Link]("Median: " + median);
}
}
Sample Input:
Enter number of elements: 5
Enter elements: 7 1 4 9 3
Sample Output:
Median: 4.0
Program 94: Smallest and Second Smallest
Java Code:
import [Link];
class SmallestTwo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of elements: ");
int n = [Link]();
int[] arr = new int[n];
[Link]("Enter elements: ");
for (int i = 0; i < n; i++) arr[i] = [Link]();
int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE;
for (int x : arr) {
if (x < first) { second = first; first = x; }
else if (x < second && x != first) second = x;
}
[Link]("Smallest : " + first);
[Link]("Second Smallest: " + second);
}
}
Sample Input:
Enter number of elements: 5
Enter elements: 30 10 50 20 40
Sample Output:
Smallest : 10
Second Smallest: 20
Program 95: Add Two Distances (Kilometer and Meter)
Java Code:
class DistanceKM {
int km, m;
DistanceKM(int km, int m) { [Link]=km; this.m=m; }
DistanceKM add(DistanceKM d) {
int totalM = this.m + d.m;
int totalKM = [Link] + [Link] + totalM / 1000;
return new DistanceKM(totalKM, totalM % 1000);
}
void display() { [Link](km + " km " + m + " m"); }
public static void main(String[] args) {
DistanceKM d1 = new DistanceKM(3, 700);
DistanceKM d2 = new DistanceKM(2, 500);
[Link]("D1 = "); [Link]();
[Link]("D2 = "); [Link]();
[Link]("Sum = "); [Link](d2).display();
}
}
Sample Output:
D1 = 3 km 700 m
D2 = 2 km 500 m
Sum = 6 km 200 m
Program 96: Largest and Second Largest
Java Code:
import [Link];
class LargestTwo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of elements: ");
int n = [Link]();
int[] arr = new int[n];
[Link]("Enter elements: ");
for (int i = 0; i < n; i++) arr[i] = [Link]();
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int x : arr) {
if (x > first) { second = first; first = x; }
else if (x > second && x != first) second = x;
}
[Link]("Largest : " + first);
[Link]("Second Largest: " + second);
}
}
Sample Input:
Enter number of elements: 5
Enter elements: 30 10 50 20 40
Sample Output:
Largest : 50
Second Largest: 40
Program 97: Delete Element from Array by Position
Java Code:
import [Link];
class DeleteElement {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of elements: ");
int n = [Link]();
int[] arr = new int[n];
[Link]("Enter elements: ");
for (int i = 0; i < n; i++) arr[i] = [Link]();
[Link]("Enter position to delete (1-based): ");
int pos = [Link]() - 1;
for (int i = pos; i < n-1; i++) arr[i] = arr[i+1];
[Link]("Array after deletion: ");
for (int i = 0; i < n-1; i++) [Link](arr[i] + " ");
[Link]();
}
}
Sample Input:
Enter number of elements: 5
Enter elements: 10 20 30 40 50
Enter position to delete (1-based): 3
Sample Output:
Array after deletion: 10 20 40 50
Program 98: Store and Display Patient Information
Java Code:
import [Link];
class PatientInfo {
String name; int patientNumber, age;
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of patients: ");
int n = [Link](); [Link]();
PatientInfo[] patients = new PatientInfo[n];
for (int i = 0; i < n; i++) {
patients[i] = new PatientInfo();
[Link]("Name: "); patients[i].name = [Link]();
[Link]("Patient Number: "); patients[i].patientNumber =
[Link]();
[Link]("Age: "); patients[i].age = [Link]();
[Link]();
}
[Link]("\n--- Patient Details ---");
for (PatientInfo p : patients)
[Link]("Name: " + [Link] + " | No: " + [Link] + "
| Age: " + [Link]);
}
}
Sample Input:
Enter number of patients: 2
Name: Alice Patient Number: 1001 Age: 35
Name: Bob Patient Number: 1002 Age: 42
Sample Output:
--- Patient Details ---
Name: Alice | No: 1001 | Age: 35
Name: Bob | No: 1002 | Age: 42
Program 99: Insert Element at Specified Position in Array
Java Code:
import [Link];
class InsertElement {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of elements: ");
int n = [Link]();
int[] arr = new int[n+1];
[Link]("Enter elements: ");
for (int i = 0; i < n; i++) arr[i] = [Link]();
[Link]("Enter value to insert: ");
int val = [Link]();
[Link]("Enter position (1-based): ");
int pos = [Link]() - 1;
for (int i = n; i > pos; i--) arr[i] = arr[i-1];
arr[pos] = val;
[Link]("Array after insertion: ");
for (int i = 0; i <= n; i++) [Link](arr[i] + " ");
[Link]();
}
}
Sample Input:
Enter number of elements: 5
Enter elements: 10 20 40 50 60
Enter value to insert: 30
Enter position (1-based): 3
Sample Output:
Array after insertion: 10 20 30 40 50 60
Program 100: 3-Digit Prime Numbers in Descending Order
Java Code:
class ThreeDigitPrimes {
static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i <= [Link](n); i++) if (n % i == 0) return false;
return true;
}
public static void main(String[] args) {
[Link]("3-Digit Primes (Descending): ");
for (int i = 999; i >= 100; i--) if (isPrime(i)) [Link](i + " ");
[Link]();
}
}
Sample Output:
3-Digit Primes (Descending): 997 991 983 977 971 ... 101
Program 101: Volume of Sphere Using Constructor (III)
Java Code:
class SphereVolIII {
double radius;
SphereVolIII(double radius) {
[Link] = radius;
double vol = (4.0/3) * 3.14 * radius * radius * radius;
[Link]("Radius: %.1f | Volume: %.2f%n", radius, vol);
}
public static void main(String[] args) {
new SphereVolIII(3);
new SphereVolIII(5);
new SphereVolIII(8);
}
}
Sample Output:
Radius: 3.0 | Volume: 113.04
Radius: 5.0 | Volume: 523.33
Radius: 8.0 | Volume: 2143.57
Program 102: Display All Perfect Numbers up to 1000
Java Code:
class PerfectNumbers {
static boolean isPerfect(int n) {
int sum = 0;
for (int i = 1; i <= n/2; i++) if (n % i == 0) sum += i;
return sum == n;
}
public static void main(String[] args) {
[Link]("Perfect numbers up to 1000: ");
for (int i = 2; i <= 1000; i++) if (isPerfect(i)) [Link](i + "
");
[Link]();
}
}
Sample Output:
Perfect numbers up to 1000: 6 28 496
Program 103: Find Factors of a Number
Java Code:
import [Link];
class Factors {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int n = [Link]();
[Link]("Factors of " + n + ": ");
for (int i = 1; i <= n; i++) if (n % i == 0) [Link](i + " ");
[Link]();
}
}
Sample Input:
Enter a number: 24
Sample Output:
Factors of 24: 1 2 3 4 6 8 12 24
Program 104: Area and Perimeter of Rectangle and Circle (Constructor
Overloading)
Java Code:
class Shape {
double val1, val2;
boolean isCircle;
Shape(double radius) { this.val1 = radius; [Link] = true; }
Shape(double length, double width) { this.val1=length; this.val2=width;
[Link]=false; }
void display() {
if (isCircle)
[Link]("Circle -> Area: %.2f | Perimeter: %.2f%n",
3.14*val1*val1, 2*3.14*val1);
else
[Link]("Rectangle -> Area: %.2f | Perimeter: %.2f%n",
val1*val2, 2*(val1+val2));
}
public static void main(String[] args) {
new Shape(7).display();
new Shape(5, 9).display();
}
}
Sample Output:
Circle -> Area: 153.86 | Perimeter: 43.96
Rectangle -> Area: 45.00 | Perimeter: 28.00
Program 105: GCD and LCM of Two Numbers
Java Code:
import [Link];
class GcdLcm {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter two numbers: ");
int a = [Link](), b = [Link]();
int x = a, y = b;
while (b != 0) { int t = b; b = a % b; a = t; }
[Link]("GCD = " + a);
[Link]("LCM = " + (x * y) / a);
}
}
Sample Input:
Enter two numbers: 12 18
Sample Output:
GCD = 6
LCM = 36
Program 106: Area and Perimeter of Rectangle and Circle (Method Overloading)
Java Code:
class ShapeMethod {
void area(double radius) { [Link]("Circle Area : %.2f%n",
3.14*radius*radius); }
void area(double l, double w) { [Link]("Rectangle Area : %.2f%n",
l*w); }
void perimeter(double radius) { [Link]("Circle Perimeter: %.2f%n",
2*3.14*radius); }
void perimeter(double l, double w) { [Link]("Rect Perimeter :
%.2f%n", 2*(l+w)); }
public static void main(String[] args) {
ShapeMethod sm = new ShapeMethod();
[Link](5); [Link](5);
[Link](4, 7); [Link](4, 7);
}
}
Sample Output:
Circle Area : 78.50
Circle Perimeter: 31.40
Rectangle Area : 28.00
Rect Perimeter : 22.00
Program 107: PCM Marks – Total and Average
Java Code:
import [Link];
class PCMMarks {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter Physics marks: "); double physics =
[Link]();
[Link]("Enter Chemistry marks: "); double chemistry =
[Link]();
[Link]("Enter Mathematics marks: "); double maths =
[Link]();
double total = physics + chemistry + maths;
[Link]("Total : %.2f%n", total);
[Link]("Average: %.2f%n", total / 3);
}
}
Sample Input:
Enter Physics marks: 85
Enter Chemistry marks: 90
Enter Mathematics marks: 78
Sample Output:
Total : 253.00
Average: 84.33
Program 108: Add Two Times (hh:mm:ss)
Java Code:
class Time {
int hours, minutes, seconds;
Time(int h, int m, int s) { hours=h; minutes=m; seconds=s; }
Time add(Time t) {
int s = [Link] + [Link];
int m = [Link] + [Link] + s / 60;
int h = [Link] + [Link] + m / 60;
return new Time(h % 24, m % 60, s % 60);
}
void display() { [Link]("%02d:%02d:%02d%n", hours, minutes,
seconds); }
public static void main(String[] args) {
Time t1 = new Time(5, 45, 50);
Time t2 = new Time(3, 20, 25);
[Link]("T1 = "); [Link]();
[Link]("T2 = "); [Link]();
[Link]("Sum = "); [Link](t2).display();
}
}
Sample Output:
T1 = 05:45:50
T2 = 03:20:25
Sum = 09:06:15