Home | FAQ | Contact me

Temperature conversion

I wanted to implement a Fahrenheit to Celsius and Celsius to Fahrenheit API.

Inside this code

In terms of beginning Java samples you have:

  • Use of floating-point arithmetic.
Eclipse tip: Which project file am I editing?

If you have a hard time drawing a correspondance between the file you're editing in Eclipse and the project, package, etc. in the Package Explorer pane (because you want to commit it for example), click the icon.

package com.etretatlogiciels.samples.converters;

/**
 * I just wanted to implement a Fahrenheit to Celsius converter in Java.
 *
 * TODO: There are too many decimals given in the answers; round these.
 *
 * @author Russell Bateman, April 2009
 */
public class TemperatureConversion
{
  public static float celsiusToFahrenheit( float celsius )
  {
    return( celsius * 9 / 5 ) + 32;
  }

  public static float fahrenheitToCelsius( float fahrenheit )
  {
    return( fahrenheit - 32 ) * 5 / 9;
  }

  public static void main( String[] args )
  {
    System.out.println( "-273C is "
                        + TemperatureConversion.celsiusToFahrenheit( -273 )
                        + " degrees Fahrenheit" );
    System.out.println( "-40F is "
                        + TemperatureConversion.fahrenheitToCelsius( -40 )
                        + " degrees Celsius" );
    System.out.println( "100C is "
                        + TemperatureConversion.celsiusToFahrenheit( 100 )
                        + " degrees Fahrenheit" );
    System.out.println();
    System.out.println( "Bake bread at "
                        + TemperatureConversion.fahrenheitToCelsius( 500 )
                        + " degrees Celsius (500F)" );
    System.out.println( "Good barbecue slowly reaches "
                        + TemperatureConversion.fahrenheitToCelsius( 205 )
                        + " degrees Celsius (205)" );
  }
}
// vim: set tabstop=2 shiftwidth=2 noexpandtab:

Console output

-273C is -459.4 degrees Fahrenheit -40F is -40.0 degrees Celsius 100C is 212.0 degrees Fahrenheit Bake bread at 260.0 degrees Celsius (500F) Good barbecue slowly reaches 96.111115 degrees Celsius (205F)