Java ProgramsBasics & I/OConvert Fahrenheit to Celsius

Convert Fahrenheit to Celsius in Java

beginner·  Basics & I/O  ·  Conversions

Problem

Converting Fahrenheit back to Celsius reverses the same linear relationship — subtract 32 first, then multiply by 5/9.

Given a temperature in Fahrenheit, convert it to Celsius.

Input
fahrenheit = 98.6
Output
98.6°F = 37.0°C

Java Program

Java
public class ConvertFahrenheitToCelsius { public static void main(String[] args) { double fahrenheit = 98.6; double celsius = (fahrenheit - 32) * 5.0 / 9.0; // standard F-to-C formula System.out.println(fahrenheit + "°F = " + celsius + "°C"); } }

Output

98.6°F = 37.0°C

Core Logic

Applying the formula C = (F - 32) * 5/9 directly converts the Fahrenheit value into its Celsius equivalent.

How It Works
  1. 1fahrenheit holds 98.6.
  2. 2(fahrenheit - 32) * 5.0 / 9.0 evaluates to 37.0.
  3. 3The subtraction happens first because of the parentheses, matching the formula's order of operations.
  4. 4Both values are printed together on one line.
For fahrenheit = 98.6, (98.6 - 32) * 5.0 / 9.0 gives 37.0.
💡

Key Point: The parentheses around fahrenheit - 32 aren't optional — without them, 5.0 / 9.0 would be computed first and multiplied into just the 32, giving a completely different (wrong) result.

Key Concepts

doublearithmetic expression

Approach 2: Java 8

Java
import java.util.function.DoubleUnaryOperator; public class ConvertFahrenheitToCelsiusLambda { public static void main(String[] args) { double fahrenheit = 98.6; // The conversion formula is stored as a reusable lambda DoubleUnaryOperator toCelsius = f -> (f - 32) * 5.0 / 9.0; double celsius = toCelsius.applyAsDouble(fahrenheit); System.out.println(fahrenheit + "°F = " + celsius + "°C"); } }

Output

98.6°F = 37.0°C

Core Logic

The conversion formula can be stored as a reusable lambda instead of being written inline.

How It Works
  1. 1DoubleUnaryOperator toCelsius = f -> (f - 32) * 5.0 / 9.0; stores the formula as a lambda.
  2. 2toCelsius.applyAsDouble(fahrenheit) calls it, returning the same value the inline expression would.
  3. 3The result is printed exactly as before.
With fahrenheit = 98.6, toCelsius.applyAsDouble(98.6) returns 37.0.
💡

Key Point: Storing toFahrenheit and toCelsius as separate lambdas (see the Celsius-to-Fahrenheit page) makes it clear they're inverse operations, even though neither calls the other.

Key Concepts

DoubleUnaryOperatorfunctional interfacelambda expression

Related Programs