Constants with final

The final Keyword

Add final when a value must never change after it is set. Trying to change it is a compile error.

Example

public class Main {
    static final double GST_RATE = 0.18;     // class-level constant
    static final int MAX_LOGIN_ATTEMPTS = 3;

    public static void main(String[] args) {
        final String COMPANY = "Careeroza";  // local constant
        double price = 500;
        System.out.println(COMPANY + " invoice");
        System.out.println("GST: " + price * GST_RATE);
        System.out.println("Max attempts: " + MAX_LOGIN_ATTEMPTS);
        // GST_RATE = 0.12;  // error: cannot assign a value to final variable GST_RATE
    }
}

Output

Careeroza invoice
GST: 90.0
Max attempts: 3

Why Use Constants?

  • No "magic numbers": price * GST_RATE is clearer than price * 0.18.
  • Change the value in one place when the rule changes.
  • The compiler protects the value from accidental changes.