Java ProgramsOOPFinal Variable

Final Variable in Java

beginner·  OOP  ·  Modifiers

Problem

A variable declared final can only be assigned once — after that first assignment, any attempt to assign it again is a compile-time error.

Declare a final variable, assign it once, and use its value.

Input
balance = 1000.0
Output
Interest earned: 50.0

Java Program

Java
public class FinalVariableDemo { public static void main(String[] args) { final double INTEREST_RATE = 0.05; // assigned once, can never be reassigned double balance = 1000.0; double interest = balance * INTEREST_RATE; System.out.println("Interest earned: " + interest); } }

Output

Interest earned: 50.0

Core Logic

Marking a variable final locks in its value at the point of assignment, documenting in the code itself that it's meant to never change afterward.

How It Works
  1. 1final double INTEREST_RATE = 0.05; assigns the value once, at declaration.
  2. 2Because it's final, no line anywhere later in the method could reassign INTEREST_RATE — the compiler rejects it outright.
  3. 3balance * INTEREST_RATE reads the final variable freely — final only blocks reassignment, not reading.
  4. 4The computed interest is an ordinary, non-final variable, and could be reassigned later if needed.
With balance = 1000.0 and INTEREST_RATE = 0.05, interest comes out to 50.0.
💡

Key Point: Attempting INTEREST_RATE = 0.06; anywhere after its initial assignment would fail to compile — the compiler enforces the single-assignment rule, it's not just a naming convention.

Key Concepts

final keywordconstantsingle assignment

Related Programs