Sunday, September 24, 2023

How to Convert Fahrenheit to Celsius in Java with Example

In this Java tutorial, you will learn how to write a program to convert Fahrenheit to Celsius in Java. Fahrenheit is a thermodynamic temperature scale, where the freezing point of water is 32 degrees Fahrenheit (°F) and the boiling point of water is 212°F (at standard atmospheric pressure). This puts the boiling and freezing points of water exactly 180 degrees apart. Therefore, a degree on the Fahrenheit scale is 1/180 of the interval between the freezing point and the boiling point of water. Absolute zero is defined as -459.67°F. If you know, in the Celsius scale, the freezing point of water is at 0ºC and the boiling point of water is at 100ºC. By using these facts, you can easily deduce a formula to convert Fahrenheit temperature into Celsius.

To be frank, if you have been a Science student you already know about that formula, nothing new about it. What is more important is to learn how to convert such a formula into a computer program using Java programming language.

This is what you will learn in this tutorial. Btw, if you are an absolute Java beginner and learning Java, I suggest you take a look at a couple of introductory books about Java programming language like Java: A Beginner's Guide by Herbert Schildt, it's one of the up-to-date books in Java and covers even latest Java release, Java 8.

One more book which you can refer to learn basic features like reading input from the command prompt, converting one data type to another is the Core Java Volume I - Fundamentals by Cay S. Horstmann, one of the better books to start learning Java.

If you are one who likes to try a couple of books before settling it for one then you can also check here for a couple of more recommended books for Java beginners.





Formula to convert Fahrenheit to Celsius and vice -versa

A temperature difference of 1°F is the equivalent of a temperature difference of 0.556°C.  You can use the following formula to convert Fahrenheit temperature into Celsius temperature :

C = (F- 32) * 5 / 9

where F  is the temperature in Fahrenheit

For Celsius to Fahrenheit conversion, you can  use

F = 9 * (C / 5) + 32;

where C is the temperature on Celsius scale

Here is the chart of common temperatures in both Fahrenheit and Celsius Scale, you can use this data to write a JUnit test for our program as well :

How to convert Fahrenheit to Celsius in Java program example




How to convert Fahrenheit to Celsius in Java

This is our sample program to do this conversion. We have created two methods toFahrenheit(float C) and toCelsius(float F) to convert between Fahrenheit temperature to Celsius and vice-versa.

Both are static methods because they are utility methods and operate only on the data provided to the method and don't depend on any object state.  Both methods accept temperature in respective scale as floating-point value and convert them into other by using the above formula and return it back to the caller.

You can write a unit test to verify that behavior or you can just run the program using the main method to see how it works and what output it generates while converting between these two units.

This method is also a good example of how to accept user input in Java because it uses the Scanner class from the java.util package to read user input from the console.

We first ask the user to enter a temperature in the Fahrenheit scale and then read this input using the nextFloat() method of the Scanner class. This method returns user input from the command line as a floating-point value. 

After that, we pass this value to our conversion method toCelsius(float F) which converts this value into Celsius scale and print it into the console so that the user can see the result.



After that, we ask our user to enter a temperature into the Celsius scale and we convert that into Fahrenheit using toFahrenheit(float C) method. We once again display the result on the console for the user.




import java.util.Arrays;
import java.util.Scanner;
 
/**
* Java program to convert Fahrenheit to Celsius (ºF to ºC) and vice-versa.
*
* @author Javin 
*/
public class FahrenheitToCelsiumInJava {
 
    public static void main(String args[]) {
 
        Scanner cmd = new Scanner(System.in);
 
        // Converting Fahrenheit to Celsius
        System.out.println("Enter temperature in Fahrenheit :");
        float temperatue = cmd.nextFloat();
        float celsius = toCelsius(temperatue);
        System.out.printf("%.02f degree fahrenheit temperature 
            is equal to %.02f degree celsius %n", temperatue, celsius);
 
        // Converting Celsius to Fahrenheit
        System.out.println("Enter temperature in degree celsius :");
        temperatue = cmd.nextFloat();
        float fahrenheit = toFahrenheit(temperatue);
        System.out.printf("%.02f degree celsius is equal 
              to %.02f degree fahrenheit %n", temperatue, fahrenheit);
    }
 
    /**
     * Method to convert temperature from celsius to fahrenheit
     *
     * @param celsius
     * @return
     */
    public static float toFahrenheit(float celsius) {
        float fahrenheit = 9 * (celsius / 5) + 32;
        return fahrenheit;
    }
 
    /**
    * Converts fahrenheit temperature to celsius
     *
     * @param fahrenheit
     * @return
     */
    public static float toCelsius(float fahrenheit) {
        float celsius = (fahrenheit - 32) * 5 / 9;
        return celsius;
    }
 
}
 
Output
Enter temperature in Fahrenheit :
100
100.00 degree fahrenheit temperature is equal to 37.78 degree celsius
Enter temperature in degree celsius :
36.2
36.20 degree celsius is equal to 97.16 degree Fahrenheit


That's all about how to convert temperature from Celsius to Fahrenheit in Java.  This is actually a homework exercise for many Java courses and I have provided this solution upon one of my reader's requests, which asks me to write about it. 

It's actually a good exercise to learn Java programming because you learn how to write a program, how to use static methods in Java, and most importantly how to convert formulas into programs in Java. Let me know if you find any difficulty in understanding this example and I would be glad to explain it further.


If you like to practice coding problems like this, you would also enjoy solving the following programming challenges :
  • How do you find duplicate elements of the array in Java? [solution]
  • How do find the maximum and minimum numbers in the unsorted array? [solution]
  • Write a program to find the missing number in an integer array of 1 to 100? [solution]
  • How do you reverse an array in place in Java? [solution]
  • How to convert JSON to JavaScript? (example)
  • Write a program to find the top two numbers from an integer array? [solution]
  • How do you check if the given String is Palindrome in Java? [solution]
  • How to convert long to String in Java? (example)
  • How do you remove duplicates from an array in place? [solution]
  • How do you implement the Sieve of Eratosthenes algorithm in Java? [solution
  • How to implement a linked list data structure in Java? [solution]
  • How to remove duplicates from an array in Java? [solution]
  • How to check if an array contains a number in Java? [solution]
  • How to sort an array in place using the QuickSort algorithm? [solution]
  • How to find all pairs on an integer array whose sum is equal to a given number? [solution]

Thanks for reading this article so far. If you like this example of how to convert Fahrenheit to Celsius in Java program then please share with your friends and colleague.s If you have any questions or feedback, please ask.

P. S. - If you are looking for free Java resources to learn Java from scratch then you can also check out these free Udemy courses to learn Java. They are great resources to learn Java programming from scratch online at your own pace. 

And lastly one question for you? Which one is your favorite Java homework program? Palindrome, Prime number, Fibonacci, Factorial or this one? 

1 comment :

Anonymous said...

Do we need to do any error handling for invalid values? Also, can you program handle negative values?

Post a Comment