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[]) {
  
    double fahr, celsius;
    double lower, upper, step;

    // lower limit of temperature table
    lower = 0.0;  

    // upper limit of temperature table
    upper = 300.0;

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

  } 

}  

Previous | Next | Top
Last Modified May 31, 1998
Copyright 1997-8 Elliotte Rusty Harold
elharo@metalab.unc.edu