Delayed Assignment
The declaration of a variable and the assignment of its initial value can be done separately.
public class Main {
public static void main(String[] args) {
String contestWinner;
contestWinner = "Boaty McBoatface";
System.out.println(contestWinner);
}
}
In which case the "variable declaration" will only have the "type" and "name" components.
String contestWinner;
// type name
And the "initial assignment" will look identical to a "re-assignment".
contestWinner = "Boaty McBoatface";
// name initial value
Before an initial value is assigned to a variable, it is not allowed to be used.1
public class Main {
public static void main(String[] args) {
String contestWinner;
// This will not run, since Java knows that
// you never gave contestWinner an initial value.
System.out.println(contestWinner);
}
}
1
There is no direct use for separating declaration and initial assignment at this point, but it's a surprise tool that will help us later.