Declaring and initializing variables
In short: Declaring means giving a variable a name and type so the program reserves memory for it. Initializing means assigning it its first value. Both can be done together on one line.
In more detail: The computer must know beforehand how much memory a variable needs and what it may contain. That happens in the declaration. Afterwards it must receive a valid initial value, otherwise it contains random leftovers or null.
In Depth
Declaration, initialization, assignment:
int age; // declaration: type and name
age = 17; // initialization: first value
int height = 180; // both on one line
age = 18; // later assignment (change the value)| Step | Meaning | Effect |
|---|---|---|
| Declare | Announce name and type | Memory is reserved |
| Initialize | Assign first value | Variable is usable |
| Assign | Change value later | Old value is overwritten |
In different languages:
| Language | Example |
|---|---|
| Java, C, C# | int x = 5; (specify type) |
| Python | x = 5 (type is inferred, no declaration needed) |
| JavaScript | let x = 5;, const PI = 3.14;, formerly var |
| TypeScript | let x: number = 5; |
| Kotlin | val x = 5 (immutable), var y = 3 |
| Go | x := 5 or var x int = 5 |
Important rules:
- Local variables in Java must have a value before being read (otherwise compiler error). Attributes get default values (0,
false,null). - C/C++: Uninitialized local variables contain garbage, a common bug and security risk. Always initialize.
const/final: Value may be set only once.- Visibility (scope): A variable applies only in the block where it is declared.
- Names: Meaningful (
customerCountinstead ofa), camelCase in Java, snake_case in Python. - Several on one line:
int a = 1, b = 2;(only when clear). - Declaring functions: In C you separate declaration (prototype) and definition (body).
Errors: Using a variable before it was declared (“cannot find symbol”, “is not defined”). Declaring twice in the same scope.
See also: Initialise, Multiple variables, Variables