How to convert Celsius to Fahrenheit in Java
The two temperature scales that are most commonly used are Fahrenheit and Celsius. Knowing how to convert Celsius to Fahrenheit is useful because it allows programmers to manage temperature calculations when creating weather-related apps.
Let’s first discuss the formula for converting Celsius to Fahrenheit.
Conversion formula
Using the formula below, we can change the temperature from Celsius to Fahrenheit:
Here, is the Fahrenheit temperature, and is the Celsius temperature.
We need to apply the above formula to a provided temperature value to convert it from Celsius to Fahrenheit.
Example
Let’s suppose we have a temperature of degrees Celsius. Let’s put the value of in the formula above,
Given that ,
Implementation
Now, let’s see an example of converting a temperature in Celsius to Fahrenheit in Java:
public class CelsiusToFahrenheit {public static void main(String[] args) {double c = 30;// Using the formuladouble f = (c * 9/5) + 32;System.out.println("After converting celsius to fahrenheit the value is " + f);}}
Code explanation
Line 1: Define a public class named
CelsiusToFahrenheit.Line 2: Define the
mainmethod, which is the starting point of the Java program.Line 3: Define a double variable
cand declare and initialize it with the value. This variable represents the temperature in Celsius. Line 6: Calculate the temperature in Fahrenheit using the formula for converting Celsius to Fahrenheit. It multiplies the Celsius temperature (
c) byand adds to the result. The calculated Fahrenheit temperature is stored in the variable f.Line 7: Print the result.
Free Resources