Celsius to Fahrenheit Example in Java
On this page (9sections)
Introduction
Celsius To Fahrenheit is a classic Java console program that demonstrates the concept with complete source code and sample output. Conversion programs transform values between formats, units or representations.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Formula
[F] = [C] * 9/5 + 32
where,
[F] is the temperature in Fahrenheit scale
[C] is the temperature in Celsius scale
Celsius To Fahrenheit Example Program
import java.util.Scanner;
public class CelsiusToFahrenheit {
public static void main(String[] args) {
System.out.println("Enter a temperature in Celsius: ");
Scanner in = new Scanner(System.in);
double Fahrenheit = 0;
if(in.hasNextDouble()){
double celsius = in.nextDouble();
Fahrenheit = (celsius * 9.0 / 5.0) + 32;
}
System.out.println("The temperature in Fahrenheit is: "+Fahrenheit);
}
}
Sample Output
Enter a temperature in Celsius:
115
The temperature in Fahrenheit is: 239.0
When to use
Use unit conversion programs when reading sensor data, building calculators, or localizing measurements for users.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
import java.util.Scanner;imports a class used later in the program. -
A
println/printcall writes text to the console — part of the sample output below. -
A
Scannerreads typed input from the keyboard (System.in). -
double Fahrenheit = 0;updates a variable used in the calculation or output. -
The
ifstatement runs the nested code only when the condition is true. -
double celsius = in.nextDouble();updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below.
Best Practices
- Use
double(orBigDecimalfor money) to avoid integer division rounding errors. - Apply multiplication before addition — match the formula order exactly.
- Validate input with
hasNextDouble()before reading, as shown in the Scanner examples.
Common Mistakes
- Using integer division (
9/5as1) instead of floating-point (9.0/5.0). - Applying the wrong formula order —
(C + 32) * 9/5is not the same asC * 9/5 + 32. - Forgetting to close the
Scannerwhen finished (callin.close()in longer programs).