Declaration is not to declare "value" to a variable; it's to declare the type of the variable.
Assignment is simply the storing of a value to a variable.
Initialization is the assignment of a value to a variable at the time of declaration.
These definitions also applies to fields.
int i; // simple declaration
i = 42 // simple assignment
int[] arr = { 1, 2, 3 };
// declaration with initialization, allows special shorthand syntax for arrays
arr = { 4, 5, 6 }; // doesn't compile, special initializer syntax invalid here
arr = new int[] { 4, 5, 6 }; // simple assignment, compiles fine
However, it should be mentioned that "initialization" also has a more relaxed definition of "the first assignment to a variable", regardless of where it happens.
int i; // local variable declaration
if (something) i = 42;
System.out.println(i);
// compile time error: The local variable i may not have been initialized
This, however, compiles:
int i; // the following also compiles if i were declared final
if (something) i = 42;
else i = 666;
System.out.println(i);
Here i
can be "initialized" from two possible locations, by simple assignments. Because of that, if i
was an array, you can't use the special array initializer shorthand syntax with this construct.
So basically "initialization" has two possible definitions, depending on context:
- In its narrowest form, it's when an assignment is comboed with declaration.
- It allows, among other things, special array shorthand initializer syntax
- More generally, it's when an assignment is first made to a variable.
- It allows, among other things, assignments to a
final
variable at multiple places.
- The compiler would do its best to ensure that exactly one of those assignments can happen, thus "initializing" the
final
variable
There's also JVM-context class and instance initialization, OOP-context object initialization, etc.