bhylu.com

Advertisements

Java Convert a Temperature Without Integer Division

A conversion formula is also an exercise in operand types. If the ratio is evaluated as integer division first, the result can be wrong even when assigned to a double.

Understand the idea

For Celsius to Fahrenheit, use a fractional ratio and add the offset after scaling. This recipe reports a boolean check to avoid making the displayed decimal formatting depend on a machine locale. A user-facing converter should also label the input and output units, reject non-finite values when appropriate and define its rounding/display policy.

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) {
        double celsius = 25;
        double fahrenheit = celsius * 9.0 / 5.0 + 32.0;
        System.out.println(fahrenheit);
    }
}

Expected output

77.0

Multiplication and division operate on floating-point operands because of the decimal literals. Testing known reference points, such as freezing and boiling at the intended scale, can expose a misplaced offset or integer ratio. Those tests check the formula’s contract, not the accuracy of a real measurement sensor.

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