go to previous page   go to home page   go to next page hear noise highlighting

Answer:

123 coins / 5 pirates is 24 coins per pirate.

123 % 5 is 3 coins left over for the parrot.


Constants

Often in a program you want to give a name to a constant value. For example you might have a tax rate of 0.045 for durable goods and a tax rate of 0.038 for non-durable goods. These are constants, because their value is not going to change during a run of the program. It is convenient to give these constants a name. This can be done:

The reserved word final tells the compiler that the value will not change. The names of constants follow the same rules as the names for variables. (Programmers sometimes use all capital letters for constants; but that is a matter of personal style, not part of the language.)


public class CalculateTax
{
  public static void main ( String[] arg )
  {
    final double DURABLE = 0.045;
    final double NONDURABLE = 0.038;

    . . . . . .
  }
}

Now the constants can be used in expressions like:

taxamount = gross * DURABLE ;

But the following is a syntax error:

// try (and fail) to change the tax rate.
DURABLE = 0.441;   

In your programs, use a named constant like DURABLE rather than using a literal like 0.045. There are two advantages in doing this:

  1. Constants make your program easier to read and check for correctness.
  2. If a constant needs to be changed (for instance if the tax rates change) all you need to do is change the declaration of the constant. You don't have to search through your program for every occurrence of a specific number.

QUESTION 18:

Could an ordinary variable be used to give a value a name? What is another advantage of using final?


go to previous page   go to home page   go to next page