allthingsare๐Ÿ…ฟ๏ธ.com Books โฌ…๏ธ Back allthingsare

โ€œCast all your anxiety on him because he cares for you.โ€

[1 Peter 5:7]


final and Constants


11.2.1 What is final?

In Java, the final keyword is one of the simplest yet most powerful tools for making your code safe and predictable.
The word final literally means โ€œcannot changeโ€ โ€” once something is declared final, its value or behavior is locked in place.

In practice, final is used in three major ways:

  1. Final variables:
    When you declare a variable as final, you guarantee that it can be assigned only once.
    After that, its value is frozen โ€” any attempt to change it causes a compiler error.
    This is how you create true constants in Java.

  2. Final methods:
    When you declare a method as final, subclasses cannot override it.
    This is useful when you want to make sure some core logic always runs exactly as written, even if someone extends your class.

  3. Final classes:
    When you mark a whole class as final, no other class can inherit from it.
    This fully locks the design, protecting it from being modified through subclassing.


In this chapter, we focus on using final for variables, especially for constants that should never change during the lifetime of the program.


11.2.2 Using final for Constants

A constant is a value in your program that is guaranteed not to change once itโ€™s set.
Good examples include:

  • The value of Pi,

  • Tax rates,

  • Conversion factors (like kilometers to miles),

  • Fixed configuration values (like the maximum number of users allowed).

In Java, the standard way to create a true constant is to combine final with static:

  • final makes the value unchangeable.

  • static means the value belongs to the class itself, not to any one object.
    You donโ€™t want each object to have its own copy โ€” that wastes memory and can cause confusion.


Naming Convention:
Constants in Java use all-uppercase letters with words separated by underscores.
This instantly tells other programmers, โ€œThis is a constant. Do not try to modify it!โ€

Example:

java
public class Constants { public static final double PI = 3.14159; public static void main(String[] args) { System.out.println("Value of PI: " + Constants.PI); } }

Key ideas here:

  • public static final means everyone can see it, itโ€™s class-level, and immutable.

  • Once PI is set to 3.14159, itโ€™s impossible to change it in any later code.

  • If you try Constants.PI = 2.5; โ†’ compile-time error!


Why bother?

  • Using final prevents accidental bugs where a developer mistakenly reassigns a value that should stay constant.

  • It makes your intention crystal clear: โ€œThis value is universal, safe, and will not vary.โ€


Where do you see this in the real world?

  • The Math class uses constants like Math.PI and Math.E.

  • Frameworks use constants for status codes, default settings, or API endpoints.

  • Large projects have Config or Constants classes that hold all important fixed values in one place.


11.2.3 Mini Lab: Combining static and final Together

Letโ€™s put the whole concept together in a practical, realistic mini lab.

Below is a simple class that:

  • Declares a static final constant for Pi.

  • Uses a non-static field (radius) for instance-specific data.

  • Combines both in a method to calculate the area of a circle.

java
public class Circle { public static final double PI = 3.14159; // constant for Pi private double radius; // instance field public Circle(double radius) { this.radius = radius; } public double area() { return PI * radius * radius; } public static void main(String[] args) { Circle c = new Circle(5); System.out.println("Circle area: " + c.area()); } }

How does this work in detail?

  • PI is declared public static final.

    • Public so it can be used anywhere.

    • Static so thereโ€™s only one copy shared by all Circle objects.

    • Final so its value can never change, which guarantees that all calculations are consistent.

  • radius is not static โ€” each Circle object has its own unique radius.

  • The area() method combines the constant and the specific radius to calculate the result.


Key lessons here:

  • Use static final for shared, fixed facts that must never change.

  • Use instance fields for data that can differ for each object.

  • Combining both makes your design clear, robust, and safe.

  • Anyone reading the code knows immediately: PI is universal, radius is per circle.