Java Reference
In-Depth Information
For example, the names
BRANCH_COUNT
and
WINDOW_COUNT
can be given values that
cannot be changed by your code as follows:
public static final int
BRANCH_COUNT = 10;
public static final int
WINDOW_COUNT = 10;
Constants defined this way must be placed outside of the
main
method and, when we
start having more methods, outside of any other methods. This is illustrated in Display 1.8.
When we start writing programs and classes with multiple methods, you will see that
the defined constants can be used in all the methods of a class. However, if a constant is
only going to be used inside a single method, then it can be defined inside the method
without the keyword
public
.
Display 1.8
Comments and a Named Constant
1
/**
2
Program to show interest on a sample account balance.
3
Author: Jane Q. Programmer.
4
E-mail Address: janeq@somemachine.etc.etc.
5
Last Changed: September 21, 2004.
6
*/
7
public class
ShowInterest
8 {
9
public static final double
INTEREST_RATE = 2.5;
10
11
public static void
main(String[] args)
12 {
13
double
balance = 100;
14
double
interest;
//as a percent
15
16 interest = balance * (INTEREST_RATE / 100.0);
17 System.out.println("On a balance of $" + balance);
18 System.out.println("you will earn interest of $"
19 + interest);
20 System.out.println("All in just one short year.");
21 }
22
23 }
Although it would not be as clear,
it is legal to place the definition of
INTEREST_RATE
here instead.
Sample Dialogue
On a balance of $100.0
you will earn interest of $2.5
All in just one short year.