Consider this:
public class TestClass { private String a; private String b; public TestClass() { a = "initialized"; } public void doSomething() { String c; a.notify(); // This is fine b.notify(); // This is fine - but will end in an exception c.notify(); // "Local variable c may not have been initialised" } }
I don't get it. "b" is never initialized but will give the same run-time error as "c", which is a compile-time error. Why the difference between local variables and members?
Edit: making the members private was my initial intention, and the question still stands...
Should we declare a local variable without an initial value, we get an error. This error occurs only for local variables since Java automatically initializes the instance variables at compile time (it sets 0 for integers, false for boolean, etc.).
There will be no default values or ability to run the code. It will be a compile time error and your code won't run. If the variables were class fields they would get default values for certain types or null otherwise.
The value in an uninitialized variable is one of: zero, a compiler dependent value (such as 0xCC's in visual studio), or data previously stored in that memory location (old data).
Local variables are declared mostly to do some calculation. So it's the programmer's decision to set the value of the variable and it should not take a default value. If the programmer, by mistake, did not initialize a local variable and it takes a default value, then the output could be some unexpected value.
The language defines it this way.
Instance variables of object type default to being initialized to null. Local variables of object type are not initialized by default and it's a compile time error to access an undefined variable.
See section 4.12.5 for SE7 (same section still as of SE14) http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5
Here's the deal. When you call
TestClass tc = new TestClass();
the new
command performs four important tasks:
false
, objects to null
).So your fields 'a' and 'b' are both initiated to null
, and 'a' is re-initiated in the constructor. This process is not relevant for method calling, so local variable 'c' is never initialized.
HTH
PS: for the gravely insomniac, read this.
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