Java ProgramsBasics & I/OCalculate Salary

Calculate Salary in Java

beginner·  Basics & I/O  ·  Arithmetic

Problem

Hourly pay is the simplest salary model — a fixed rate per hour, multiplied by however many hours were worked.

Given an hourly pay rate and the number of hours worked, calculate the total pay.

Input
hourlyRate = 25.0, hoursWorked = 160.0
Output
Salary: 4000.0

Java Program

Java
public class CalculateSalary { public static void main(String[] args) { double hourlyRate = 25.0; double hoursWorked = 160.0; double salary = hourlyRate * hoursWorked; // rate multiplied by hours worked System.out.println("Salary: " + salary); } }

Output

Salary: 4000.0

Core Logic

Multiplying the hourly rate by the hours worked gives the total pay directly, in a single expression.

How It Works
  1. 1hourlyRate holds 25.0 and hoursWorked holds 160.0.
  2. 2hourlyRate * hoursWorked evaluates to 4000.0.
  3. 3The result is stored in salary and printed with a label.
For an hourly rate of 25.0 and 160.0 hours worked, 25.0 * 160.0 gives 4000.0.
💡

Key Point: This computes pay from hours worked, which is a different scenario from combining several fixed salary components like basic pay and allowances — that combination is covered separately by the Gross Salary page.

Key Concepts

doublemultiplication

Approach 2: Java 8

Java
import java.util.function.DoubleBinaryOperator; public class CalculateSalaryLambda { public static void main(String[] args) { double hourlyRate = 25.0; double hoursWorked = 160.0; // The multiplication logic is stored as a lambda, named for what it computes DoubleBinaryOperator payFor = (rate, hours) -> rate * hours; double salary = payFor.applyAsDouble(hourlyRate, hoursWorked); System.out.println("Salary: " + salary); } }

Output

Salary: 4000.0

Core Logic

The multiplication can be wrapped in a named lambda, turning 'compute pay' into a small reusable function.

How It Works
  1. 1DoubleBinaryOperator payFor = (rate, hours) -> rate * hours; stores the multiplication logic as a lambda.
  2. 2payFor.applyAsDouble(hourlyRate, hoursWorked) calls it, returning the same result the inline multiplication would.
  3. 3The result is printed exactly as before.
With hourlyRate = 25.0 and hoursWorked = 160.0, payFor.applyAsDouble(25.0, 160.0) returns 4000.0.
💡

Key Point: The same payFor lambda works for any employee's hours, since the rate and hours are passed in rather than being fixed inside the lambda itself.

Key Concepts

DoubleBinaryOperatorfunctional interfacelambda expression

Related Programs