Calculate Electricity Bill in Java
Problem
The simplest electricity billing model charges the same fixed rate for every unit consumed — one multiplication, no tiers or thresholds involved.
Given the number of units consumed and a flat rate per unit, calculate the total electricity bill.
Java Program
public class CalculateElectricityBill {
public static void main(String[] args) {
double units = 250.0;
double ratePerUnit = 5.0;
double bill = units * ratePerUnit; // flat rate applied to every unit
System.out.println("Electricity Bill: " + bill);
}
}Output
Core Logic
Multiplying the units consumed by the flat rate per unit gives the total bill directly, in a single expression.
- 1
unitsholds250.0andratePerUnitholds5.0. - 2
units * ratePerUnitevaluates to1250.0. - 3The result is stored in
billand printed with a label.
units = 250.0 at a flat rate of 5.0 per unit, 250.0 * 5.0 gives 1250.0.Key Point: Real electricity bills usually charge different rates for different consumption slabs — for example, a cheaper rate for the first 100 units and a higher rate beyond that — which needs conditional logic rather than a single flat-rate multiplication like this one.
Key Concepts
Approach 2: Java 8
import java.util.function.DoubleBinaryOperator;
public class CalculateElectricityBillLambda {
public static void main(String[] args) {
double units = 250.0;
double ratePerUnit = 5.0;
// The multiplication logic is stored as a lambda, named for what it computes
DoubleBinaryOperator billFor = (u, rate) -> u * rate;
double bill = billFor.applyAsDouble(units, ratePerUnit);
System.out.println("Electricity Bill: " + bill);
}
}
Output
Core Logic
The multiplication can be wrapped in a named lambda, turning 'compute a bill' into a small reusable function.
- 1
DoubleBinaryOperator billFor = (u, rate) -> u * rate;stores the multiplication logic as a lambda. - 2
billFor.applyAsDouble(units, ratePerUnit)calls it, returning the same result the inline multiplication would. - 3The result is printed exactly as before.
units = 250.0 and ratePerUnit = 5.0, billFor.applyAsDouble(250.0, 5.0) returns 1250.0.Key Point: Naming the lambda billFor keeps its purpose clear even though the underlying operation is just multiplication, the same pattern used across this topic's other flat-rate calculations.