Java ProgramsBasics & I/OCalculate Electricity Bill

Calculate Electricity Bill in Java

beginner·  Basics & I/O  ·  Arithmetic

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.

Input
units = 250.0, ratePerUnit = 5.0
Output
Electricity Bill: 1250.0

Java Program

Java
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

Electricity Bill: 1250.0

Core Logic

Multiplying the units consumed by the flat rate per unit gives the total bill directly, in a single expression.

How It Works
  1. 1units holds 250.0 and ratePerUnit holds 5.0.
  2. 2units * ratePerUnit evaluates to 1250.0.
  3. 3The result is stored in bill and printed with a label.
For 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

doublemultiplication

Approach 2: Java 8

Java
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

Electricity Bill: 1250.0

Core Logic

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

How It Works
  1. 1DoubleBinaryOperator billFor = (u, rate) -> u * rate; stores the multiplication logic as a lambda.
  2. 2billFor.applyAsDouble(units, ratePerUnit) calls it, returning the same result the inline multiplication would.
  3. 3The result is printed exactly as before.
With 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.

Key Concepts

DoubleBinaryOperatorfunctional interfacelambda expression

Related Programs