JB Header
Java program to convert from Fahrenheit to Celsius with examples
Introduction This tutorial first goes through the formulae for conversion of temperature from Fahrenheit to Celsius and vice versa. It then provides Java programs to convert from Fahrenheit to Celsius and back, along with explanation of code. Formulae for conversion between Fahrenheit and Celsius => Temperature in Celsius = (Temperature in Fahrenheit - 32) * 5/9
=> Temperature in Fahrenheit = (Temperature in Celsius * 9/5) + 32 Java program to convert Fahrenheit to Celsius
Java program to convert Fahrenheit to Celsius
package com.javabrahman.generaljava;
import java.util.Scanner;
public class FahrenheitToCelsius {
  public static void main(String args[]){
    System.out.print("Enter the temperature in Fahrenheit: ");
    Scanner scanner=new Scanner(System.in);
    float fahrenheit=scanner.nextFloat();
    float celsius=(fahrenheit-32)*5/9;
    System.out.println("Temperature in Celsius: "+celsius);
  }
}
 OUTPUT of the above code
Enter the temperature in Fahrenheit: 100
Temperature in Celsius: 37.77778
Explanation of the code
  • In the main() method of FahrenheitToCelsius class, first the temperature in Fahrenheit is taken as input as a primitive float value using a java.util.Scanner instance from the console.
  • The value in Fahrenheit is then converted to corresponding value in Celsius using the conversion formula and the converted value is printed as output.
  • As an example, temperature in Fahrenheit is input as 100 degrees and the corresponding temperature in Celsius is printed as 37.77778 degrees.
Java program to convert Celsius to Fahrenheit
Java program to convert Celsius to Fahrenheit
package com.javabrahman.generaljava;
import java.util.Scanner;
public class CelsiusToFahrenheit {
  public static void main(String args[]){
    System.out.print("Enter the temperature in Celsius: ");
    Scanner scanner=new Scanner(System.in);
    float celsius=scanner.nextFloat();
    float fahrenheit=(celsius*9/5)+32;
    System.out.println("Temperature in Fahrenheit: "+fahrenheit);
  }
}
 OUTPUT of the above code
Enter the temperature in Celsius: 38
Temperature in Fahrenheit: 100.4
Explanation of the code
  • In the main() method of CelsiusToFahrenheit class, first the temperature in Celsius is taken as input as a primitive float value using a java.util.Scanner instance from the console.
  • The value in Celsius is then converted to corresponding value in Fahrenheit using the conversion formula and the converted value is printed as output.
  • As an example, temperature in Celsius is input as 38 degrees and the corresponding temperature in Fahrenheit is printed as 100.4 degrees.