Calculate Salary in Java
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.
Java Program
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
Core Logic
Multiplying the hourly rate by the hours worked gives the total pay directly, in a single expression.
- 1
hourlyRateholds25.0andhoursWorkedholds160.0. - 2
hourlyRate * hoursWorkedevaluates to4000.0. - 3The result is stored in
salaryand printed with a label.
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
Approach 2: Java 8
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
Core Logic
The multiplication can be wrapped in a named lambda, turning 'compute pay' into a small reusable function.
- 1
DoubleBinaryOperator payFor = (rate, hours) -> rate * hours;stores the multiplication logic as a lambda. - 2
payFor.applyAsDouble(hourlyRate, hoursWorked)calls it, returning the same result the inline multiplication would. - 3The result is printed exactly as before.
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.