Temperature Conversion in Java

Here’s a simple program to convert temperatures between degrees Celcius, Fahrenheit and Kelvin written in Java. There’s no GUI used here - all output is done via the command line.

The forumulae for the conversions were obtained from Temperature conversion forumlas on Wikipedia.

File: Converter.java

/**
* Conversion between temperatures in Celcius, Fahrenheit and Kelvin
* Uses conversion forumulas from the wikipedia:
* http://en.wikipedia.org/wiki/Temperature_conversion_formulas
* User: www.tiposaurus.co.uk
* Date: 27-Dec-2005
*/
public class Converter {
  public Converter()
  {
   
  }
   
  // Method to convert from degrees Celcius to degrees Fahrenheit
  public static float celciusToFahrenheit(float degCelcius)
  {
    float degFahrenheit;
    degFahrenheit = degCelcius * 9/5 + 32;
    return degFahrenheit;
  }
   
  // Method to convert from degrees Fahrenheit to degrees Celcius
  public static float fahrenheitToCelcius(float degFahrenheit)
  {
    float degCelcius;
    degCelcius =  (degFahrenheit - 32) * 5/9;
    return degCelcius;
  }
   
  // Method to convert from degrees Celcius to degrees Kelvin
  public static float celciusToKelvin(float degCelcius)
  {
    float degKelvin;
    degKelvin = degCelcius + 273.15f;
    return degKelvin;
  }
   
  // Method to convert from degrees Kelvin to degrees Celcius
  public static float kelvinToCelcius(float degKelvin)
  {
    float degCelcius;
    degCelcius = degKelvin - 273.15f;
    return degCelcius;
  }
   
  // Main method demonstrating usage of above methods
  public static void main(String[] args)
  {
    System.out.print("100 degrees Celcius in Fahrenheit is: ");
    System.out.println(celciusToFahrenheit(100));
     
    System.out.print("-40 degrees Fahrenheit in Celcius is: ");
    System.out.println(fahrenheitToCelcius(-40));
     
    System.out.print("0 degrees Celcius in Kelvin is: ");
    System.out.println(celciusToKelvin(0));
     
    // to convert from Kelvin to Fahrenheit, combine two methods:
    System.out.print("373.15 degrees Kelvin in Fahrenheit is: ");
    System.out.println(celciusToFahrenheit(kelvinToCelcius(373.15f)));
  }
}

Comments