EMZETT.
Login

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)
StepMeaningEffect
DeclareAnnounce name and typeMemory is reserved
InitializeAssign first valueVariable is usable
AssignChange value laterOld value is overwritten

In different languages:

LanguageExample
Java, C, C#int x = 5; (specify type)
Pythonx = 5 (type is inferred, no declaration needed)
JavaScriptlet x = 5;, const PI = 3.14;, formerly var
TypeScriptlet x: number = 5;
Kotlinval x = 5 (immutable), var y = 3
Gox := 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 (customerCount instead of a), 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