final variables and constants
32 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A tax rate or an exam pass mark must never change while the program runs. One careless assignment elsewhere could break every result.
final local variables
A final variable is a variable that can be given a value only once. After it has a value, any line that tries to change it is a compile error.
A GST rate must not change halfway through a bill. As in Constants and final (opens in a new tab), a final local gets its value once; it may also get it later, once on every path of an if/else.
Example 1 · A final local variable
public class GstDemo { public static void main(String[] args) { final int gstPercent = 18; int price = 1500; int gst = price * gstPercent / 100; System.out.println("Price: Rs. " + price); System.out.println("GST: Rs. " + gst); System.out.println("Total: Rs. " + (price + gst));
final String result; int marks = 64; if (marks >= 35) { result = "Pass"; } else { result = "Fail"; } System.out.println("Result: " + result); }}Price: Rs. 1500 GST: Rs. 270 Total: Rs. 1770 Result: Pass
What this code does
gstPercentis fixed for the whole method;finalmakes that promise visible and checked.resultgets its value later, but exactly once on each path of theif/else, which is allowed.
Example 2 · Mistake: giving a final variable a new value
public class FinalErrorDemo { public static void main(String[] args) { final int maxAttempts = 3; System.out.println("Attempts allowed: " + maxAttempts); maxAttempts = 5; }}FinalErrorDemo.java:5: error: cannot assign a value to final variable maxAttempts
maxAttempts = 5;
^
1 errorWhat this code does
maxAttemptsalready has a value, so javac refuses the second assignment.- If the value really must change, the variable should not be
final.
gstPercent++ is refused too, because it also stores a new value. A method parameter can be final as well: in void pay(final int amount), the method cannot change amount.
final fields: set once, then read-only
A roll number must never change once a student is admitted. A final field gets its value exactly once, at its declaration or in the constructor; after that, no method can change it.
Example 3 · A final field set in the constructor
class Student { private final int rollNo; private String name;
Student(int rollNo, String name) { this.rollNo = rollNo; this.name = name; }
int getRollNo() { return rollNo; }
String getName() { return name; }
void setName(String name) { this.name = name; }}
public class FinalFieldDemo { public static void main(String[] args) { Student s1 = new Student(101, "Aarav"); Student s2 = new Student(102, "Priya"); s1.setName("Aarav Sharma"); System.out.println(s1.getRollNo() + " " + s1.getName()); System.out.println(s2.getRollNo() + " " + s2.getName()); }}101 Aarav Sharma 102 Priya
What this code does
- Each student gets its own
rollNoonce, in the constructor; there is no setter for it. - A final field is still per object: Aarav has 101 and Priya has 102. Only
namecan change later.
This fits encapsulation: make the field private final, give it a getter and no setter, as in Read-only fields and computed values (opens in a new tab). A setter would assign it again, which javac refuses.
Blank final fields
A blank final is a final field declared without a value, like private final String accountNo;. Every constructor must give it a value exactly once.
A final field with no value on its line, like private final String accountNo;, is a blank final. javac checks that every constructor gives it a value exactly once.
Example 4 · Mistake: a constructor that forgets the final field
class Account { private final String accountNo; private int balance;
Account(String accountNo, int balance) { this.accountNo = accountNo; this.balance = balance; }
Account(int balance) { this.balance = balance; }}
public class BlankFinalDemo { public static void main(String[] args) { new Account(500); }}BlankFinalDemo.java:12: error: variable accountNo might not have been initialized
}
^
1 errorWhat this code does
- The second constructor never sets
accountNo, so an account made with it would have no number. - Fix: set it there too, or write
this("NEW-000", balance);to reuse the first constructor.
The same rule gives two more messages:
- No constructor at all →
variable accountNo not initialized in the default constructor. - Set twice in one constructor →
variable accountNo might already have been assigned.
A constructor that starts with this(...) does not set the field itself; the constructor it calls does, as in Constructor chaining (opens in a new tab).
Constants: static final
A constant is a static final field: one fixed value for the whole class that can never change. Its name is written in UPPER_SNAKE_CASE, like PASS_MARK.
The pass mark is the same for every student and never changes. Make it a constant: static final, one copy for the class that no line can change, named in UPPER_SNAKE_CASE like PASS_MARK.
Example 5 · static final constants
class Exam { static final int MAX_MARKS = 100; static final int PASS_MARK = 35;
static String result(int marks) { if (marks < 0 || marks > MAX_MARKS) { return "Invalid marks"; } if (marks >= PASS_MARK) { return "Pass"; } return "Fail"; }}
public class ConstantDemo { public static void main(String[] args) { System.out.println("Pass mark: " + Exam.PASS_MARK + "/" + Exam.MAX_MARKS); System.out.println("72: " + Exam.result(72)); System.out.println("30: " + Exam.result(30)); System.out.println("120: " + Exam.result(120)); System.out.println("Circle area (r = 2): " + Math.PI * 2 * 2); }}Pass mark: 35/100 72: Pass 30: Fail 120: Invalid marks Circle area (r = 2): 12.566370614359172
What this code does
- The names
PASS_MARKandMAX_MARKSexplain themselves, unlike a bare35or100. - Constants are read with the class name, exactly like
Math.PI, and no line anywhere can change them.
You already know one constant: Math.PI. A named constant beats typing 35 in ten places: readers see what it means, and you change it in one spot.
static final field must get its value at the declaration or in a static block.A final reference does not freeze the object
final int[] marks sounds like the marks can never change, yet marks[0] = 75; compiles. final protects the variable, the reference it holds, not the array or object it points to.
Example 6 · A final array can still change inside
public class FinalArrayDemo { public static void main(String[] args) { final int[] marks = {70, 85, 60}; marks[0] = 75; for (int i = 0; i < marks.length; i++) { marks[i] = marks[i] + 5; } System.out.println(marks[0] + " " + marks[1] + " " + marks[2]); }}80 90 65
What this code does
finalfixes which arraymarkspoints to, not the numbers stored in it, so every change to an element compiles.- Adding
marks = new int[3];would pointmarksat a new array:cannot assign a value to final variable marks.
The same goes for objects: a final Wallet w can still call w.add(50), but w = new Wallet(0); is an error. Methods and classes can be final too; that is covered in final and inheritance (opens in a new tab).
Fix the error
Fix the final variable error
Read the error, then pick the line that fixes it.
Round 1 of 4
The limit is fixed at 3 attempts; this should count one used attempt and print 1/3.
Error
error: cannot assign a value to final variable maxAttempts
Next step
Check your understanding
12 quick questions