I have this code:
MyClass object;
.... some code here where object may or may not be initialised...
if (object.getId > 0) {
....
}
Which results in a compile error: object
may not have been initialised, which is fair enough.
Now I change my code to this:
MyClass object;
.... some conditional code here where object may or may not be initialised...
if (object != null && object.getId > 0) {
....
}
I get the same compile error! I have to initialise object
to null:
MyClass object = null;
So what's the difference between not initialising an object, and initialising to null? If I declare an object without initialisation isn't it null anyway?
Thanks
null
(or to a default primitive value, if they are primitives)It's a language-definition thing.
The language states that variables of METHOD-scope MUST be manually initialized -- if you want them to start out as NULL, you must explicitly say so -- if you fail to do so, they are basically in an undefined state.
Contrarily, the language states that variables of CLASS-scope do not need to be manually initialized -- failure to initialize them results in them automatically getting initialized to NULL -- so you don't have to worry about it.
As far as the difference between the two states (null vs. undefined), yes they are basically the same -- but the language dictates that you need to initialize a variable (whether that's done automatically for you or not, depending on the variable's scope).
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