Calculate Gross Salary in Java
Problem
Gross salary is a sum of several separate components, unlike a single hourly-rate calculation — basic pay plus each allowance, added together.
Given a basic salary and several allowances, calculate the total gross salary.
Java Program
public class CalculateGrossSalary {
public static void main(String[] args) {
double basic = 20000.0;
double hra = 8000.0;
double da = 4000.0;
double allowance = 2000.0;
double grossSalary = basic + hra + da + allowance; // sum of all salary components
System.out.println("Gross Salary: " + grossSalary);
}
}Output
Core Logic
Adding basic pay, HRA, DA, and the other allowance together gives the gross salary directly, in a single expression.
- 1
basic,hra,da, andallowancehold20000.0,8000.0,4000.0, and2000.0. - 2
basic + hra + da + allowanceevaluates to34000.0. - 3The result is stored in
grossSalaryand printed with a label.
basic = 20000.0, hra = 8000.0, da = 4000.0, and allowance = 2000.0, the four values add up to 34000.0.Key Point: This combines several fixed salary components, which is a different scenario from computing pay from an hourly rate and hours worked — that calculation is covered separately by the Salary page.
Key Concepts
Approach 2: Java 8
import java.util.function.DoubleBinaryOperator;
public class CalculateGrossSalaryLambda {
public static void main(String[] args) {
double basic = 20000.0;
double hra = 8000.0;
double da = 4000.0;
double allowance = 2000.0;
// One "add" lambda, reused to fold all four components into a single total
DoubleBinaryOperator add = (x, y) -> x + y;
double grossSalary = add.applyAsDouble(add.applyAsDouble(add.applyAsDouble(basic, hra), da), allowance);
System.out.println("Gross Salary: " + grossSalary);
}
}
Output
Core Logic
A single 'add two amounts' lambda can be reused three times in a row to combine all four components, instead of writing out separate + operations.
- 1
DoubleBinaryOperator add = (x, y) -> x + y;stores the addition logic as one reusable lambda. - 2
add.applyAsDouble(basic, hra)combines the first two components. - 3That result is fed into
add.applyAsDouble(..., da), and the result of that intoadd.applyAsDouble(..., allowance), chaining the same lambda three times to fold all four values into one total.
add across 20000.0, 8000.0, 4000.0, and 2000.0 produces the same 34000.0 the inline sum would.Key Point: Reusing one add lambda repeatedly is the same idea behind a stream's reduce() operation — combining a sequence of values two at a time using a single, consistent operation.