bhylu.com

Advertisements

Java Calculate an Area with Meaningful Units

A rectangle’s area uses two lengths expressed in compatible units. Type choice and validation matter even for a familiar formula.

Understand the idea

Reject impossible negative dimensions before multiplying. For whole-unit dimensions, a long result avoids some small int-range failures, but it is still finite. Widen before multiplication and use checked arithmetic when the contract must reject overflow. If measurements are decimal or physical tolerances matter, choose an appropriate numeric and unit model rather than silently mixing centimetres with metres.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

public class Main {
    public static void main(String[] args) {
        int widthCm = 13, heightCm = 8;
        if (widthCm < 0 || heightCm < 0) throw new IllegalArgumentException("negative dimension");
        long areaCm2 = Math.multiplyExact((long) widthCm, heightCm);
        System.out.println(areaCm2);
    }
}

Expected output

104

The cast ensures multiplication occurs as long arithmetic, and the variable name records square centimetres. Zero width would produce zero area under this contract. A different domain may require strictly positive dimensions, so validation should reflect the meaning of the measurement rather than a memorised formula.

Check the official Java documentation for detailed contracts and supported options.