Temperature Converter – Java Program
This Java program converts temperatures between Celsius and Fahrenheit. It includes two methods:
celsiusToFahrenheit(double celsius)
: Converts a temperature from Celsius to Fahrenheit.fahrenheitToCelsius(double fahrenheit)
: Converts a temperature from Fahrenheit to Celsius.
Java Code
// TemperatureConverter.java
public class TemperatureConverter {
// Method to convert Celsius to Fahrenheit
public static double celsiusToFahrenheit(double celsius) {
return (celsius * 9/5) + 32;
}
// Method to convert Fahrenheit to Celsius
public static double fahrenheitToCelsius(double fahrenheit) {
return (fahrenheit - 32) * 5/9;
}
public static void main(String[] args) {
// Example usage
double celsius = 25;
double fahrenheit = 77;
System.out.println(celsius + "°C is equal to " + celsiusToFahrenheit(celsius) + "°F");
System.out.println(fahrenheit + "°F is equal to " + fahrenheitToCelsius(fahrenheit) + "°C");
}
}
Explanation
This program consists of the following components:
Methods
- celsiusToFahrenheit(double celsius): This method takes a temperature in Celsius as input and converts it to Fahrenheit using the formula
(celsius * 9/5) + 32
. - fahrenheitToCelsius(double fahrenheit): This method takes a temperature in Fahrenheit as input and converts it to Celsius using the formula
(fahrenheit - 32) * 5/9
.
Main Method
The main
method demonstrates how to use these conversion methods. It initializes two example temperatures, one in Celsius and one in Fahrenheit, and then prints the converted values to the console.