Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between non-initialisation and initialising to null?

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

like image 591
Richard H Avatar asked Nov 10 '10 14:11

Richard H


2 Answers

  • fields (member-variables) are initialized to null (or to a default primitive value, if they are primitives)
  • local variables are not initialized and you are responsible for setting the initial value.
like image 77
Bozho Avatar answered Oct 06 '22 00:10

Bozho


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).

like image 25
Bane Avatar answered Oct 06 '22 00:10

Bane