Java program to convert Fahrenheit to Celsius

Quick links

Write a Java program to input temperature in Fahrenheit from user and convert to Celsius. How to convert Fahrenheit to Celsius in Java programming.

In the previous post, I explained to convert temperature from Celsius to Fahrenheit. In this post, we learn how to convert Fahrenheit to Celsius in Java.

Example
Input

Enter temperature in Fahrenheit : 255.5

Output

255.5 degree Fahrenheit is equal to 402.2999893426895 degree Celsius.

Required knowledge

Arithmetic operators, Data types, Basic Input/Output

How to convert Fahrenheit to Celsius

Before we write single line of Java code, you must know relation between Fahrenheit and Celsius. Mathematical equation to convert Fahrenheit to Celsius is given by:

Convert Fahrenheit to Celsius formula

C = (F - 32) * (5 / 9)

or

C = (F - 32) / (9 / 5)

or

C = (F - 32) / 1.8

We can use any of the above three equation in our program to convert temperature from Fahrenheit to Celsius.

Program to convert Fahrenheit to Celsius

/**
 * Java program to convert Fahrenheit to Celsius.
 */

import java.util.Scanner;

public class TemperatureConverter {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        
        /* Input temperature in Fahrenheit from user */
        System.out.print("Enter temperature in Fahrenheit: ");
        float F = in.nextFloat();

        /* Convert Fahrenheit to Celsius */
        float C = (F - 32) * (9f / 5);

        /* Print temperature in Celsius */
        System.out.println(F + " degree Fahrenheit is equal to " + C + " degree Celsius.");

    }
}

Note:
In statement, float C = (F - 32) * (9f / 5). I have used 9f. If you simply write (9 / 5), integer division will get performed instead of floating point division. Hence, you need to typecast either 9 or 5 to float.

To convert an integer to float in Java, you can use any of the following approaches.

float val = 9f; // Append f to integer
val = (float) 9; // Prefix with typecast operator

Output

Enter temperature in Fahrenheit: 255.5
255.5 degree Fahrenheit is equal to 402.3 degree Celsius.

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>