Video lecture
Watch on YouTube(opens in a new tab)Sub topic 14
Final Variables and Constants
A variable can often be assigned a new value while a program runs. Sometimes, though, a value should stay the same. Java’s final keyword lets you tell the compiler that a variable must not be assigned more than once.
The compiler is the tool that checks Java code and turns it into a program that can run. If your code tries to assign a new value to a final variable, the compiler reports an error.
This chapter assumes you can read a basic Java program and know how to declare and assign variables.
Making a variable final
Put final before the variable’s type:
final int DAYS_IN_WEEK = 7;
Here, DAYS_IN_WEEK is assigned the value 7. A later statement such as DAYS_IN_WEEK = 8; would cause a compiler error.
A final variable can still be used in calculations. For example, DAYS_IN_WEEK * 2 produces 14. The calculation does not change DAYS_IN_WEEK.
A constant is a named value that is intended to stay the same. Constants help explain what a number means and give you one place to change it if a rule changes. For example, DAYS_IN_WEEK is clearer than repeatedly writing 7.
Worked example: planning pizza
This program calculates how many pizzas a group needs. Save it as PizzaPlan.java.
class PizzaPlan {
static final int SLICES_PER_PIZZA = 8;
public static void main(String[] args) {
int guests = 7;
boolean largeAppetites = true;
final int slicesEach;
if (largeAppetites) {
slicesEach = 2;
} else {
slicesEach = 1;
}
final int slicesNeeded = guests * slicesEach;
final int pizzasNeeded =
(slicesNeeded + SLICES_PER_PIZZA - 1)
/ SLICES_PER_PIZZA;
guests = 9;
System.out.println("Slices needed: " + slicesNeeded);
System.out.println("Pizzas needed: " + pizzasNeeded);
// slicesEach = 3; // Error if this line is uncommented
}
}Compile and run it:
javac PizzaPlan.java
java PizzaPlanThe output is:
Slices needed: 14
Pizzas needed: 2Here is what happens:
SLICES_PER_PIZZAgives a name to the rule that each pizza has eight slices.slicesEachis declared without a value. Theifandelsestatements then assign it a value. Only one of those paths runs.- Seven guests need two slices each, so
slicesNeededis14. - The pizza calculation rounds up: fourteen slices need two whole pizzas.
- Changing
gueststo9does not changeslicesNeeded. Its value was calculated and assigned earlier.
The last point matters: final does not make a calculation update itself. Calculate a final value after you have the inputs you intend to use.
Assigning after declaration
You do not have to assign a final local variable on the same line where you declare it. A local variable is a variable declared inside a method, such as main.
In the example, both paths assign slicesEach before it is used. The compiler checks that the variable has a value on every path that reaches the calculation.
If you removed the else path, the compiler could not be sure that slicesEach had a value when largeAppetites was false. The program would not compile. Assigning slicesEach again after the if and else would also cause an error.
A final local variable may be declared and never used. But if you read it, Java must be able to check that it was assigned first.
Class constants and names
In the pizza program, SLICES_PER_PIZZA is declared with both static and final.
finalprevents another assignment to the variable.staticmakes the variable belong to the class rather than to one particular object created from that class.
A static final value is often called a class constant. It is useful for a fixed rule that belongs to the whole class.
By convention, class constant names use capital letters with underscores between words, such as SLICES_PER_PIZZA. A convention is a common way of writing code. Java does not require these capital letters, but they make constants easier to spot.
Local final variables usually use the same naming style as other local variables, such as slicesNeeded.
Final fields and parameters
A field is a variable declared in a class but outside its methods. A field can belong to each object created from the class. An object is a value created from a class.
A constructor is code that runs when an object is created. It can assign a final field for that object. Save this example as TicketDemo.java:
class Ticket {
final int seatNumber;
Ticket(final int number) {
this.seatNumber = number;
// number = 99; // Error if this line is uncommented
}
}
class TicketDemo {
public static void main(String[] args) {
Ticket first = new Ticket(12);
Ticket second = new Ticket(15);
System.out.println(first.seatNumber);
System.out.println(second.seatNumber);
}
}Run it with:
javac TicketDemo.java
java TicketDemoThe output is:
12
15Each ticket has its own seatNumber. The constructor assigns that field once for each new ticket. The word this refers to the ticket currently being created.
The constructor’s number is a parameter: a variable that receives a value passed to the constructor. It is also final, so the constructor cannot assign a different value to number.
A final field can instead be assigned where it is declared. If it is left for a constructor to assign, the compiler checks that it is assigned as required before the constructor finishes normally. Do not rely on a default value as the assignment for a final field.
Final references can point to changeable objects
For a primitive variable such as int, final keeps its stored value from being reassigned. A reference variable, however, holds a reference to an object. The reference tells Java which object the variable refers to.
Making a reference variable final keeps it from being reassigned to refer to a different object. It does not always prevent changes inside the object.
An array is an object that holds a sequence of values. Save this example as FinalArrayDemo.java:
class FinalArrayDemo {
public static void main(String[] args) {
final int[] scores = {4, 5};
scores[0] = 9;
System.out.println(scores[0]);
// scores = new int[] {7, 8}; // Error if uncommented
}
}Run it with:
javac FinalArrayDemo.java
java FinalArrayDemoIt prints 9. The statement scores[0] = 9 changes the first value inside the array. It does not reassign the scores reference. The commented-out statement would try to make scores refer to a different array, so it would cause an error.
The same distinction applies to a static final reference: the reference cannot be reassigned, but the object it refers to may still be changeable.
When to use final
Use final when another assignment would be a mistake. It helps readers understand your intent and lets the compiler catch accidental assignments.
| Situation | Useful choice |
|---|---|
| A shared rule such as slices per pizza | A `static final` class constant |
| A calculated value that should not be reassigned | A final local variable |
| A ticket’s seat number that should stay fixed | A final field |
| An array whose contents must never change | More protection than just a final reference |
final does not make a value secret. It also does not stop an array or other changeable object from being edited through another reference.
Exercises
Exercise
A program has final int boxes = 4; and then calculates int total = boxes * 3;. What is total, and has boxes changed?
Show answer
total is 12. boxes remains 4 because the calculation did not reassign it.
Exercise
A final local variable is assigned in an if path but not in its else path. Can the program read it after the if statement?
Show answer
Not unless Java can establish that it was assigned on every path reaching that read. Otherwise, the compiler reports an error.
Exercise
If scores is a final reference to an array, can scores[0] be changed? Can scores be assigned a different array?
Show answer
An array value such as scores[0] can be changed. The scores reference cannot be assigned a different array.