In computer science, variables are like named containers for storing data. Your program uses variables to hold numbers, text, and other information so it can use them later.
Variables can be mutable (changeable) or immutable (unchangeable). Mutable variables can be reassigned new values, while immutable variables keep their initial value. This affects how the program manages memory and ensures code predictability.
graph TD
A[Variable Declaration] --> B{Mutability Choice}
B --> C[Mutable Variables]
B --> D[Immutable Variables]
C --> E[Can be reassigned]
D --> F[Cannot be reassigned]
E --> G[Flexible but riskier]
F --> H[Safer and more predictable]
style C fill:#ffcdd2
style D fill:#c8e6c9
style G fill:#ffcdd2
style H fill:#c8e6c9
Mutable variables can be changed after they are created. They are useful for counters, user input, and any data that needs to be updated during program execution.
varname="Fadi";name="William";// Can be reassignedSystem.out.println("Hello, "+name+"!");// Output: Hello, William!
varname="Fadi"name="William"// Can be reassignedprintln("Hello, $name!")// Output: Hello, William!
letmyName="Fadi";myName="William";// Can be reassignedconsole.log(`Hello, ${myName}!`);// Output: Hello, William!
varname="Fadi";name="William";// Can be reassignedprint("Hello, $name!");// Output: Hello, William!
varname="Fadi"name="William"// Can be reassignedprint("Hello, \(name)!")// Output: Hello, William!
name="Fadi"name="William"# Can be reassignedprint(f'Hello, {name}!')# Output: Hello, William!