Based on my reference, primitive types have default values and Objects are null. I tested a piece of code.
public class Main {
public static void main(String[] args) {
int a;
System.out.println(a);
}
}
The line System.out.println(a);
will be an error pointing at the variable a
that says variable a might not have been initialized
whereas in the given reference, integer
will have 0
as a default value. However, with the given code below, it will actually print 0
.
public class Main {
static int a;
public static void main(String[] args) {
System.out.println(a);
}
}
What could possibly go wrong with the first code? Does class instance variable behaves different from local variables?
All member variable have to load into heap so they have to initialized with default values when an instance of class is created. In case of local variables, they don't get loaded into heap they are stored in stack until they are being used before java 7, so we need to explicitly initialize them.
In the first code sample,
a
is amain
method local variable. Method local variables need to be initialized before using them.In the second code sample,
a
is class member variable, hence it will be initialized to default value .In java the default initialization is applicable for only instance variable of class member it isn't applicable for local variables.
yes, instance variable will be initialized to default value, for local variable you need to initialize before use
These are the main factors involved:
Note 1: you must initialize final member variables on EVERY implemented constructor!
Note 2: you must initialize final member variables inside the block of the constructor itself, not calling another method that initializes them. For instance, this is NOT valid:
Note 3: arrays are Objects in Java, even if they store primitives.
Note 4: when you initialize an array, all of its items are set to default, independently of being a member or a local array.
I am attaching a code example, presenting the aforementioned cases:
Local variables do not get default values. Their initial values are undefined with out assigning values by some means. Before you can use local variables they must be initialized.
There is a big difference when you declare a variable at class level (as a member ie. as a field) and at method level.
If you declare a field at class level they get default values according to their type. If you declare a variable at method level or as a block (means anycode inside {}) do not get any values and remain undefined until somehow they get some starting values ie some values assigned to them.