Course contentsShow
← Computer Science
Lesson 148 of 2,8724. Introduction to ProgrammingFree lesson

Constants and Immutability

Declaring values that cannot change after initialization using const or final.

Constants and Immutability

You'll learn how to declare values that can never change once they're set, protecting your data from accidental modification.

What Are Constants?

In programming, a constant is a variable whose value is set once and can never be changed afterward. Think of it like engraving your name on a trophy—once it's carved in, it's permanent. Unlike regular variables that can be reassigned new values throughout your program, constants remain fixed from the moment you initialize them.

Why Use Constants?

Constants serve two important purposes:

  1. Safety: They prevent accidental changes to values that should stay the same (like mathematical constants, configuration settings, or fixed rules)
  2. Clarity: They communicate to other programmers (and your future self) that this value is intentional and shouldn't be modified

Declaring Constants

Most programming languages use keywords like const or final to declare constants:

const PI = 3.14159
const MAX_USERS = 100
final TAX_RATE = 0.08

Once declared, trying to change a constant will cause an error:

const DAYS_IN_WEEK = 7
DAYS_IN_WEEK = 8  // ERROR: Cannot reassign constant!

The Concept of Immutability

Immutability is the broader idea that once something is created, it cannot be altered. Constants are immutable by design. This concept helps prevent bugs because you know certain values will never unexpectedly change during program execution.

Common uses include physical constants (like speed of light), game rules (maximum score, level count), or application settings (database names, API keys).

Key Takeaway: Constants are variables declared with const or final that lock their values after initialization, preventing accidental changes and making your code safer and more understandable.