Sub topic 14
Final Variables and Constants
A value that cannot be reassigned
A variable is a named place for a value. In Java, the word final means you can assign a value to that variable only once. Assignment means giving a variable a value.
Use final when a value should stay the same after it is set. It helps prevent accidental changes. It also tells readers that the value is meant to stay fixed.
A constant is a value that does not change. For example, the number of minutes in an hour is a useful constant. Java programmers often write constant names in capital letters, with underscores between words: MINUTES_PER_HOUR.
A worked example
Save this program in a file named TripTime.java:
class TripTime {
static final int MINUTES_PER_HOUR = 60;
public static void main(String[] args) {
int hours = 2;
final int firstTripMinutes;
firstTripMinutes = hours * MINUTES_PER_HOUR;
System.out.println("First trip: " + firstTripMinutes);
hours = 3;
System.out.println("Next trip: " + (hours * MINUTES_PER_HOUR));
System.out.println("First trip is still: " + firstTripMinutes);
}
}To compile and run it, enter these commands in the same folder as the file. A compiler is a program that checks Java code and prepares it to run.
javac TripTime.java
java TripTimeThe output is:
First trip: 120
Next trip: 180
First trip is still: 120The program declares firstTripMinutes with final, then assigns it a value on the next line. Giving a variable its first value is called initialization. You can initialize a final variable when you declare it or later, as this example does.
The program then changes hours from 2 to 3. That does not change firstTripMinutes: its value was calculated and stored when the assignment ran.
The compiler must be able to check that a final variable has been assigned before you use it. It must also check that you do not assign it a second time. For example, adding firstTripMinutes = 180; after the first assignment would cause a compile error.
Sharing a constant
MINUTES_PER_HOUR is declared outside main, inside the class. A class is a way to group Java code and data. The word static means the variable belongs to the class rather than to an individual object created from it. Other methods in this class can use the same constant.
Use a named constant when a fixed value has a clear meaning or is needed in more than one place. MINUTES_PER_HOUR is easier to understand than an unexplained 60 repeated throughout a program.
A final value does not always have to be known when you write the program. In the example, firstTripMinutes gets its value from a calculation while the program runs.
Practice
Exercise
If hours changes after firstTripMinutes is assigned, does firstTripMinutes change? Why?
Show answer
No. The assignment stores the calculated value, 120. Later changes to hours do not recalculate it.
Exercise
What happens if you assign a second value to MINUTESPERHOUR?
Show answer
The compiler reports an error because the variable is final and already has a value.