Convert Temperature from Celsius to Fahrenheit in Java

Topic

In this Java program, we will learn how to convert a temperature from Celsius to Fahrenheit. This type of program is often asked in beginner-level interviews to test your understanding of basic arithmetic operations and input/output in Java.

The formula to convert Celsius to Fahrenheit is: Fahrenheit = (Celsius * 9/5) + 32.

Examples

  • Input: 0 °C → Output: 32.0 °F
  • Input: 100 °C → Output: 212.0 °F
  • Input: -40 °C → Output: -40.0 °F (interesting edge case where both scales match)

Interviewer Expectations

The interviewer expects you to:

  • Understand and apply a given formula correctly
  • Use arithmetic operations with floating-point numbers
  • Display formatted output using System.out.println
  • Write clean and readable Java code

Approach

To convert Celsius to Fahrenheit:

  1. Declare a variable for Celsius temperature.
  2. Apply the formula: fahrenheit = (celsius * 9 / 5) + 32.
  3. Print the result.

Dry Run:

Let’s dry run the example where Celsius = 25:


Fahrenheit = (25 * 9 / 5) + 32
           = (225 / 5) + 32
           = 45 + 32
           = 77.0

Java Program

public class TemperatureConverter {
  public static void main(String[] args) {
    double celsius = 25;
    double fahrenheit = (celsius * 9 / 5) + 32;

    System.out.println("Celsius: " + celsius);
    System.out.println("Fahrenheit: " + fahrenheit);
  }
}
Celsius: 25.0
Fahrenheit: 77.0

Possible Followup Questions with Answers

1. How do you convert Fahrenheit to Celsius?

You can use the reverse formula: Celsius = (Fahrenheit - 32) * 5 / 9.

2. How would you accept user input for Celsius in your program?

import java.util.Scanner;

public class TemperatureConverter {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter temperature in Celsius: ");
    double celsius = scanner.nextDouble();
    double fahrenheit = (celsius * 9 / 5) + 32;

    System.out.println("Fahrenheit: " + fahrenheit);
  }
}

3. What happens if you use integer division accidentally?

If you write celsius * 9 / 5 and celsius is an integer, you might lose precision. Always use double for accurate results in temperature conversion.


Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...