Java Reference
In-Depth Information
For example, the names
BRANCH_COUNT
and
WINDOW_COUNT
can be given values that can-
not be changed by your code as follows:
public static final
int
BRANCH_COUNT = 10;
public static final
int
WINDOW_COUNT = 10;
These constant definitions must be placed outside of the
main
method and, when we
start having more methods, outside of any other methods. This is illustrated in Dis-
play 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.
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
}
Although it would not be as clear,
it is legal to place the definition of
INTEREST_RATE
here instead.
22
23
}
Sample Dialogue
On a balance of $100.0
you will earn interest of $2.5
All in just one short year.