Java ProgramsBasics & I/OConvert Celsius to Fahrenheit

Convert Celsius to Fahrenheit in Java

beginner·  Basics & I/O  ·  Conversions

Problem

Fahrenheit and Celsius are related by a fixed linear formula — multiply by 9/5 and add 32 to convert one to the other.

Given a temperature in Celsius, convert it to Fahrenheit.

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

Java Program

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

Output

37.0°C = 98.6°F

Core Logic

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

How It Works
  1. 1celsius holds 37.0.
  2. 2celsius * 9.0 / 5.0 + 32 evaluates to 98.6.
  3. 3Using 9.0 and 5.0 instead of 9 and 5 forces floating-point division, avoiding an accidental integer division.
  4. 4Both values are printed together on one line.
For celsius = 37.0, 37.0 * 9.0 / 5.0 + 32 gives 98.6.
💡

Key Point: Writing 9.0 / 5.0 instead of 9 / 5 matters — integer division would silently truncate 9 / 5 to 1, giving a wrong result.

Key Concepts

doublearithmetic expression

Approach 2: Java 8

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

Output

37.0°C = 98.6°F

Core Logic

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

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

Key Point: Once toFahrenheit exists as a lambda, it can be reused for any number of Celsius values without repeating the formula.

Key Concepts

DoubleUnaryOperatorfunctional interfacelambda expression

Related Programs