Parentheses in Java

Sometimes the default order of evaluation isn't what you want. For instance, the formula to change a Fahrenheit temperature to a Celsius temperature is C = (5/9) (F - 32) where C is degrees Celsius and F is degrees Fahrenheit. You must subtract 32 from the Fahrenheit temperature before you multiply by 5/9, not after. You can use parentheses to adjust the order much as they are used in the above formula. The next program prints a table showing the conversions from Fahrenheit and Celsius between zero and three hundred degrees Fahrenheit every twenty degrees.

// Print a Fahrenheit to Celsius table

class FahrToCelsius  {

  public static void main (String args[]) {
  
    // lower limit of temperature table
    double lower = 0.0;  

    // upper limit of temperature table
    double upper = 300.0;

    // step size
    double step  = 20.0; 
 
    double fahr = lower;
    while (fahr <= upper) { 
      double celsius = (5.0 / 9.0) * (fahr-32.0);
      System.out.println(fahr + " " + celsius);
      fahr = fahr + step;
    } 

  } 

} 

Previous | Next | Top | Cafe au Lait

Copyright 1997, 1998, 2002 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified September 12, 2002