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);
}
}
Java documentation for primitives
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.
Your global variable was not initialised anywhere. You are trying to print var i and test with values not seen / existing. It is not null or 0 nor blank.
Your case is a bit similar to this (from answer: Uninitialized int vs Integer)
but when it's comes to main method java is asking for variable initialization.
Your local variable which are i and t is similar case to the global variables.
Variables needs to be initialised. I personally think that any computing with variables needs to have an initial value or it will not exist.
Computers are currently based on physical use of computation / mathematics, so whatever rules are in Math it will also be applied to computers unless that we have entered a new stage of computing quantum or something further.
(from: http://en.wikipedia.org/wiki/Variable_(mathematics))
So given with that rule, a variable without any value for me is non existing empty = x is empty and no known way to compute emptiness because no one can see it.
You have to initialize local variables in java. Simple as that. If you however don't have a value, you could set the value to null. Note: int is a simple data type and can not have the value null, therefore I changed the class to "Integer", which is the class that would wrap around int anyhow.
Here in your program, your variable needs to carry some value as you used the variable in if-else loop and as i can see if the program go to else loop there is nothing to display as 'sizeDisplay' that's why your sizeDisplay needs to be initialized as "null".
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.