Java ProgramsBasics & I/OCalculate Gross Salary

Calculate Gross Salary in Java

beginner·  Basics & I/O  ·  Arithmetic

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.

Input
basic = 20000.0, hra = 8000.0, da = 4000.0, allowance = 2000.0
Output
Gross Salary: 34000.0

Java Program

Java
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

Gross Salary: 34000.0

Core Logic

Adding basic pay, HRA, DA, and the other allowance together gives the gross salary directly, in a single expression.

How It Works
  1. 1basic, hra, da, and allowance hold 20000.0, 8000.0, 4000.0, and 2000.0.
  2. 2basic + hra + da + allowance evaluates to 34000.0.
  3. 3The result is stored in grossSalary and printed with a label.
For 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

doubleaddition

Approach 2: Java 8

Java
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

Gross Salary: 34000.0

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.

How It Works
  1. 1DoubleBinaryOperator add = (x, y) -> x + y; stores the addition logic as one reusable lambda.
  2. 2add.applyAsDouble(basic, hra) combines the first two components.
  3. 3That result is fed into add.applyAsDouble(..., da), and the result of that into add.applyAsDouble(..., allowance), chaining the same lambda three times to fold all four values into one total.
Chaining 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.

Key Concepts

DoubleBinaryOperatorfunctional interfacelambda expression

Related Programs