0% found this document useful (0 votes)
9 views14 pages

Java Sample Programs

The document outlines various Java programming tasks including finding the largest number among four inputs, developing applications for a store and restaurant billing system, analyzing student test scores, and implementing classes for employee management and travel booking. It also covers concepts like method overloading, inheritance, interfaces, and abstract classes. Each task includes sample code and expected output for better understanding.

Uploaded by

klyl32c4xe
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)
9 views14 pages

Java Sample Programs

The document outlines various Java programming tasks including finding the largest number among four inputs, developing applications for a store and restaurant billing system, analyzing student test scores, and implementing classes for employee management and travel booking. It also covers concepts like method overloading, inheritance, interfaces, and abstract classes. Each task includes sample code and expected output for better understanding.

Uploaded by

klyl32c4xe
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

1.

Create a java program to find largest number among 4 numbers using nested if
else statement.
2. Develop a java application for ABC stores. Get the total purchase value from
the user and apply offers based on the following conditions:
i. If purchase amount is less than 10000 then apply 12% offer.
ii. If purchase amount is 10001 to 20000 then apply 18% offer.
iii. If purchase amount is 20001 to 50000 then apply 23% offer.
iv. If purchase amount is above 50000 then apply 30% offer.
Finally print the Total bill amount after deducting the offer amount.
3. Develop a java application for restaurant billing system with the following
features:
i. Display product details to the user and get the product code as a input
from the user.
ii. Apply switch case and calculate the product bill amount by getting
product quantity from the user.
iii. Provide feature which enable the user to go for multiple number of
product selection.
iv. Display Product details, product quantity, product prize and final bill
amount.
4. Implement the program to demonstrate the TestScoreAnalysis of the students. Find
the maximum and minimum scores, calculate the sum, and compute the average, and
sort the score.
5. Create an Employee class with name, jobTitle, and salary attributes. Include
methods to update the salary by a certain percentage and print the employee's details.
6. Develop a Travel Booking System with calculateFare method. A travel app
calculates fare:
 Based on distance
 Based on distance and travel class
 Based on distance, class, and number of passengers
7. Develop Student Result System with calculatePercentage method. A school system
calculates student percentage based on following terms:
 Using 3 subjects
 Using 4 subjects
 Using any number of subjects (array)
8. Create a base class Vehicle with a method speed() that prints "Maximum speed: 100
km/h". Create a subclass Car that inherits from Vehicle. In Car, override the speed()
method to print "Maximum speed: 150 km/h". Instantiate Car and call speed()
[Link] an Employee base class with properties for name, employeeId, and salary.
Implement a method calculateBonus() that returns a default bonus amount (e.g., 5% of
salary). Create subclasses Manager, Developer, and Secretary that all
extend Employee.
[Link] are building a smart home system. Some devices can be turned ON/OFF, and
some devices can be connected to WiFi.
Task:
Create two interfaces:
Switchable → turnOn(), turnOff()
Connectable → connectToWifi()
Implement:
SmartBulb (Switchable + Connectable)
Fan (Switchable only)

11. A game has different characters:


Warrior
Mage
Archer
All characters:
Have health and level
Can attack
Must use special ability differently
Task:
Create abstract class GameCharacter
Concrete method: takeDamage(int damage)
Abstract method: useSpecialAbility()

12. Develop a java application for ABCBank with method called


calculateEMI(LoanAmount, Tenure, InterestPercentage). The bank is offering
three different types of loan (Personal Loan, Home Loan, Car Loan). Derive the
properties and behaviours of ABCBank class to all the loan types class and redefine
the method calculateEMI(LoanAmount, Tenure, InterestPercentage). Finally create
objects for all the child classes and calculate EMI amount by giving total loan amount,
tenure and interest percentage.
1. Largest Number Among 4 Numbers (Nested If–Else)
import [Link];

public class LargestNumber {


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

[Link]("Enter four numbers:");


int a = [Link]();
int b = [Link]();
int c = [Link]();
int d = [Link]();

int largest;

if(a > b) {
if(a > c) {
if(a > d)
largest = a;
else
largest = d;
} else {
if(c > d)
largest = c;
else
largest = d;
}
} else {
if(b > c) {
if(b > d)
largest = b;
else
largest = d;
} else {
if(c > d)
largest = c;
else
largest = d;
}
}

[Link]("Largest number is: " + largest);


[Link]();
}
}
Sample Output
Enter four numbers:
10
45
23
12
Largest number is: 45

2. ABC Stores Offer Application


import [Link];

public class ABCStores {


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

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


double amount = [Link]();
double discount = 0;

if(amount <= 10000)


discount = amount * 0.12;
else if(amount <= 20000)
discount = amount * 0.18;
else if(amount <= 50000)
discount = amount * 0.23;
else
discount = amount * 0.30;

double finalAmount = amount - discount;

[Link]("Discount Amount: " + discount);


[Link]("Final Bill Amount: " + finalAmount);

[Link]();
}
}
Sample Output
Enter Purchase Amount:
15000
Discount Amount: 2700.0
Final Bill Amount: 12300.0

3. Restaurant Billing System


import [Link];

public class RestaurantBilling {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int choice;
double totalBill = 0;

do {
[Link]("----- MENU -----");
[Link]("1. Burger - 100");
[Link]("2. Pizza - 250");
[Link]("3. Coffee - 80");
[Link]("Enter Product Code:");
int code = [Link]();

[Link]("Enter Quantity:");
int qty = [Link]();

double price = 0;

switch(code) {
case 1: price = 100; break;
case 2: price = 250; break;
case 3: price = 80; break;
default: [Link]("Invalid Code");
}

double bill = price * qty;


totalBill += bill;
[Link]("Product Price: " + price);
[Link]("Product Quantity: " + qty);
[Link]("Bill Amount: " + bill);

[Link]("Do you want to order more? (1-Yes / 0-No)");


choice = [Link]();

} while(choice == 1);

[Link]("Final Total Bill: " + totalBill);


[Link]();
}
}
Sample Output
----- MENU -----
1. Burger - 100
2. Pizza - 250
3. Coffee - 80
Enter Product Code:
2
Enter Quantity:
2
Product Price: 250.0
Product Quantity: 2
Bill Amount: 500.0
Do you want to order more? (1-Yes / 0-No)
0
Final Total Bill: 500.0

4. Test Score Analysis


import [Link].*;
public class TestScoreAnalysis {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of students:");
int n = [Link]();

int[] scores = new int[n];


int sum = 0;
[Link]("Enter scores:");
for(int i=0; i<n; i++) {
scores[i] = [Link]();
sum += scores[i];
}
int max = scores[0], min = scores[0];
for(int i=1; i<n; i++) {
if(scores[i] > max) max = scores[i];
if(scores[i] < min) min = scores[i];
}

double avg = (double)sum/n;


[Link](scores);
[Link]("Maximum: " + max);
[Link]("Minimum: " + min);
[Link]("Sum: " + sum);
[Link]("Average: " + avg);
[Link]("Sorted Scores: " + [Link](scores));
[Link]();
}
}
Sample Output
Enter number of students:
5
Enter scores:
78 90 65 88 92
Maximum: 92
Minimum: 65
Sum: 413
Average: 82.6
Sorted Scores: [65, 78, 88, 90, 92]

5. Employee Class
import [Link];

public class Employee {


String name, jobTitle;
double salary;

Employee(String n, String j, double s) {


name = n;
jobTitle = j;
salary = s;
}

void updateSalary(double percent) {


salary += salary * percent / 100;
}

void display() {
[Link]("Name: " + name);
[Link]("Job Title: " + jobTitle);
[Link]("Salary: " + salary);
}

public static void main(String[] args) {


Employee e = new Employee("Anu", "Manager", 50000);
[Link](10);
[Link]();
}
}
Sample Output
Name: Anu
Job Title: Manager
Salary: 55000.0

6. Travel Booking System (Method Overloading)


import [Link];

public class TravelBooking {

void calculateFare(double distance) {


double fare = distance * 10;
[Link]("Fare (Normal): " + fare);
}

void calculateFare(double distance, String travelClass) {


double rate = [Link]("AC") ? 15 : 10;
double fare = distance * rate;
[Link]("Fare (" + travelClass + "): " + fare);
}

void calculateFare(double distance, String travelClass, int passengers) {


double rate = [Link]("AC") ? 15 : 10;
double fare = distance * rate * passengers;
[Link]("Total Fare for " + passengers + " passengers: " + fare);
}

public static void main(String[] args) {


TravelBooking t = new TravelBooking();
[Link](100);
[Link](100, "AC");
[Link](100, "AC", 3);
}
}
Sample Output
Fare (Normal): 1000.0
Fare (AC): 1500.0
Total Fare for 3 passengers: 4500.0

7. Student Result System (Method Overloading)


public class StudentResult {

void calculatePercentage(int s1, int s2, int s3) {


double percent = (s1 + s2 + s3) / 3.0;
[Link]("Percentage (3 Subjects): " + percent);
}

void calculatePercentage(int s1, int s2, int s3, int s4) {


double percent = (s1 + s2 + s3 + s4) / 4.0;
[Link]("Percentage (4 Subjects): " + percent);
}

void calculatePercentage(int[] marks) {


int sum = 0;
for(int m : marks) sum += m;
double percent = sum / (double)[Link];
[Link]("Percentage (Array): " + percent);
}
public static void main(String[] args) {
StudentResult s = new StudentResult();
[Link](80, 85, 90);
[Link](70, 75, 80, 85);
[Link](new int[]{60,70,80,90,100});
}
}
Sample Output
Percentage (3 Subjects): 85.0
Percentage (4 Subjects): 77.5
Percentage (Array): 80.0

8. Method Overriding (Vehicle & Car)


public class Vehicle {
void speed() {
[Link]("Maximum speed: 100 km/h");
}
}

class Car extends Vehicle {


void speed() {
[Link]("Maximum speed: 150 km/h");
}

public static void main(String[] args) {


Car c = new Car();
[Link]();
}
}
Sample Output
Maximum speed: 150 km/h

9. Employee Bonus System (Inheritance)


public class Employee {
String name;
int employeeId;
double salary;

Employee(String n, int id, double s) {


name = n;
employeeId = id;
salary = s;
}

double calculateBonus() {
return salary * 0.05;
}
}

class Manager extends Employee {


Manager(String n, int id, double s) {
super(n,id,s);
}
}

class Developer extends Employee {


Developer(String n, int id, double s) {
super(n,id,s);
}
}

class Secretary extends Employee {


Secretary(String n, int id, double s) {
super(n,id,s);
}

public static void main(String[] args) {


Manager m = new Manager("Anu",101,50000);
[Link]("Manager Bonus: " + [Link]());
}
}
Sample Output
Manager Bonus: 2500.0

10. Interfaces Example


interface Switchable {
void turnOn();
void turnOff();
}
interface Connectable {
void connectToWifi();
}

class SmartBulb implements Switchable, Connectable {


public void turnOn() {
[Link]("SmartBulb ON");
}

public void turnOff() {


[Link]("SmartBulb OFF");
}

public void connectToWifi() {


[Link]("SmartBulb Connected to WiFi");
}
}

class Fan implements Switchable {


public void turnOn() {
[Link]("Fan ON");
}

public void turnOff() {


[Link]("Fan OFF");
}

public static void main(String[] args) {


SmartBulb b = new SmartBulb();
[Link]();
[Link]();

Fan f = new Fan();


[Link]();
}
}
Sample Output
SmartBulb ON
SmartBulb Connected to WiFi
Fan ON
11. Abstract Class (GameCharacter)
abstract class GameCharacter {
int health = 100;
int level = 1;

void takeDamage(int damage) {


health -= damage;
[Link]("Remaining Health: " + health);
}

abstract void useSpecialAbility();


}

class Warrior extends GameCharacter {


void useSpecialAbility() {
[Link]("Warrior uses Sword Slash!");
}

public static void main(String[] args) {


Warrior w = new Warrior();
[Link](20);
[Link]();
}
}
Sample Output
Remaining Health: 80
Warrior uses Sword Slash!

12. ABC Bank EMI System (Method Overriding)


class ABCBank {
double calculateEMI(double loanAmount, int tenure, double interest) {
double rate = interest / (12 * 100);
double emi = (loanAmount * rate) /
(1 - [Link](1 + rate, -tenure));
return emi;
}
}

class PersonalLoan extends ABCBank { }


class HomeLoan extends ABCBank { }
class CarLoan extends ABCBank { }

public class TestBank {


public static void main(String[] args) {
PersonalLoan p = new PersonalLoan();
double emi = [Link](500000, 24, 10);
[Link]("Personal Loan EMI: " + emi);
}
}
Sample Output
Personal Loan EMI: 23072.27

Common questions

Powered by AI

The ABC Bank system uses inheritance to differentiate loan types: PersonalLoan, HomeLoan, and CarLoan, which all extend the base class ABCBank. Although the method 'calculateEMI' is not explicitly overridden in the subclasses, inheritance allows polymorphic behavior through the superclass reference. This design allows further specific extension or tailoring of EMI calculations within any subclass without altering the superclass, thereby promoting a flexible, scalable architecture .

The program uses nested if-else conditions to compare four numbers. It first compares the first number 'a' with 'b'. If 'a' is greater, it then compares 'a' with 'c'. If 'a' is greater than both, it compares 'a' with 'd'. If 'a' is greater than 'd', 'a' is the largest. Otherwise, 'd' is the largest. If 'a' is not greater than 'b', similar comparisons are made for 'b' with 'c', then with 'd', and so forth, to determine the largest .

In the Travel Booking System, inheritance and polymorphism are demonstrated through method overloading rather than classical inheritance. Different versions of the 'calculateFare' method are overloaded to handle different parameters: only distance, distance with travel class, and distance with travel class and number of passengers. Each method adjusts the fare rate: a general rate for normal travel and a higher rate for AC class travel. This polymorphic behavior is possible because each 'calculateFare' method is treated polymorphically depending on the parameters passed, allowing varied calculations within a single class context .

The test score analysis involves multiple steps. First, the number of students is inputted and stored. Their scores are then collected into an array. The program determines the maximum and minimum scores through iteration and compares each element. It also calculates the total sum and average by iterating through the array. Finally, the scores are sorted, providing a detailed overview of student performance metrics .

The restaurant billing system uses a switch-case statement to calculate the bill amount based on the product code selected by the user. The user inputs the product code (Burger, Pizza, Coffee) and quantity. Based on the product code, a price is assigned (e.g., Burger - 100, Pizza - 250, Coffee - 80). The bill amount is calculated as the product of the price and quantity, and this is added to the total bill. This calculation repeats in a loop allowing multiple orders until the user opts out .

The nested if-else statements in the ABC Stores offer application manage conditional logic by determining the discount rate based on purchase amount. If the amount is less than or equal to 10000, a 12% discount is applied. Between 10001 and 20000, an 18% discount is calculated. If between 20001 and 50000, the rate is 23%, and for amounts beyond 50000, a 30% discount is applied. This hierarchical evaluation sequence ensures only the applicable discount threshold conditions apply .

Method overloading in the Student Result System is implemented through multiple 'calculatePercentage' methods that accept different parameters. One method takes three integer parameters representing scores of three subjects and calculates the percentage by averaging them. Another method takes four integers for four subjects. A third method takes an array of scores, calculates the sum, and derives the average to find the percentage. This use of method overloading enables calculating percentages for different numbers of subjects flexibly .

Method overriding is crucial for achieving runtime polymorphism. In the Vehicle-Car example, the 'speed' method is defined in the Vehicle class and overridden in the Car subclass to provide specific behavior—printing "Maximum speed: 150 km/h" instead of "100 km/h" as in Vehicle. When a Car object calls the 'speed' method, it executes the Car's overridden version, demonstrating polymorphism as the actual method call is determined at runtime based on the object type .

Using interfaces in the smart home system design standardizes the operations for different devices, such as a SmartBulb and a Fan. The 'Switchable' interface defines general behaviors like 'turnOn' and 'turnOff'. The 'Connectable' interface provides 'connectToWifi' behavior. SmartBulb implements both, thus it can switch on/off and connect to Wifi. Fan implements only 'Switchable', hence it cannot connect to Wifi. This design using interfaces provides clear and flexible patterns for expanding the system with new devices without altering existing code, adhering to the dependency inversion principle .

Abstraction in the game characters' design is managed using an abstract class, GameCharacter, which defines general properties (health, level) and an abstract method 'useSpecialAbility'. Each character subtype like Warrior implements the 'useSpecialAbility' differently, encapsulating specific behaviors unique to each character type (

You might also like