Please see the code below. The method printTest() is printing the default value of the uninitialized variables but when it's comes to main method java is asking for variable initialization. Can anybody explain why?
public class Test1 {
public static void main(String[] args) {
int j;
String t;
System.out.println(j);
System.out.println(t);
}
}
public class Test2 {
int i;
String test;
public static void main(String[] args) {
new Test().printTest();
}
void printTest() {
System.out.println(i);
System.out.println(test);
}
}
Local variables are used mostly for intermediate calculations whereas instance variables are supposed to carry data for calculations for future and intermediate as well. Java doesnt forces to initialize instance variable and allows default value but for local variables its the developers call to adssign the value. So to avoid mistakes you need to initialize local variables.
This is a problem with what the compiler can know about.
In the case of the Main Method, the compiler knows for sure that the variables have not be initialized.
But in the case of the printTest method, the compiler does know that the could be some other method (or same package class) which initializes the class variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With