Java Program to calculate Salary of an Employee
Program
import java.util.*;
public class EmpSalary
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the basic pay");
int basic = sc.nextInt();
Salary sal = new Salary();
sal.calculateTotal(basic);
}
}
class Salary
{
private double da;
private double hra;
private double oth;
void calculateTotal(int basic)
{
da = 0.90 * basic;
hra = 0.20 * basic;
oth = 0.10 * basic;
double total = basic + da + hra + oth;
System.out.println("Basic Salary:\t" + basic);
System.out.println("Dearness Allowance:\t" + da);
System.out.println("House Rent Allowance:\t" + hra);
System.out.println("Other Allowances:\t" + oth);
System.out.println("Total Salary is: " + total);
}
}
This Java program calculates the total salary of an employee based on their basic pay and allowances such as Dearness Allowance (DA), House Rent Allowance (HRA), and Other Allowances (OTH).
-
Main Class (
EmpSalary
):- Contains the
main()
method, which is the entry point of the program. - Prompts the user to input the basic pay of the employee using the
Scanner
class. - Creates an object of the
Salary
class and calls thecalculateTotal()
method, passing the basic pay as an argument.
- Contains the
-
Class
Salary
:- Contains the logic to calculate the total salary.
- Private member variables:
da
,hra
, andoth
(for different allowances). - Method
calculateTotal(int basic)
:- Dearness Allowance (DA): Calculated as 90% of the basic pay (
0.90 * basic
). - House Rent Allowance (HRA): Calculated as 20% of the basic pay (
0.20 * basic
). - Other Allowances (OTH): Calculated as 10% of the basic pay (
0.10 * basic
). - The total salary is calculated as the sum of the basic pay, DA, HRA, and OTH.
- The method prints a detailed breakdown of the basic pay, allowances, and the total salary.
- Dearness Allowance (DA): Calculated as 90% of the basic pay (
Key Concepts Demonstrated:
-
Modularity:
- The program separates the salary calculation logic into a separate
Salary
class and method (calculateTotal
), making the code reusable and maintainable.
- The program separates the salary calculation logic into a separate
-
Encapsulation:
- The private member variables (
da
,hra
,oth
) are encapsulated within theSalary
class to restrict direct access.
- The private member variables (
-
User Input Handling:
- The
Scanner
class is used to take user input for the basic pay dynamically.
- The
-
Basic Arithmetic and Percentages:
- The allowances are calculated as percentages of the basic pay.
Output
Enter the basic pay
25000
Basic Salary: 25000
Dearness Allowance: 22500.0
House Rent Allowance: 5000.0
Other Allowances: 2500.0
Total Salary is: 55000.0