Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback, please email oracle-forums_moderators_us@oracle.com

Why local variables don't get default values?

user-43n5cAug 23 2023

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?

Comments
Post Details
Added on Aug 23 2023
5 comments
266 views