I can't understand the reason why local variables don't get a default value. If I don't initialize a local variable, the program doesn't even compile. If the variables are global, they get a default value and the program compiles.
This compiles normally and prints “0 null”:
public class Main {
public static void main(String[] args) {
Defaults defaults = new Defaults();
defaults.printDefaults();
}
public static class Defaults {
int globalNumber;
String globalWord;
public void printDefaults() {
System.out.println(globalNumber + " " + globalWord);
}
}
}
This doesn't even compile and reports the error "java: variable localNumber might not have been initialized":
public class Main {
public static void main(String[] args) {
Defaults defaults = new Defaults();
defaults.printDefaults();
}
public static class Defaults {
public void printDefaults() {
int localNumber;
String localWord;
System.out.println(localNumber + " " + localWord);
}
}
}
Why does this happen?