Dan Chaltiel
Dan Chaltiel

Reputation: 8494

Should I initialize my variables to null before using them?

I saw a lot of SO posts saying that Java set any uninitialized variable to null (like here, here or here...).

But lately, I went upon this code, written by Google here :

cur =  cr.query(builder.build(), INSTANCE_PROJECTION, selection, selectionArgs, null);
while (cur.moveToNext()) {
    String title = null;
    long eventID = 0;
    long beginVal = 0;

    // Get the field values
    eventID = cur.getLong(PROJECTION_ID_INDEX);
    beginVal = cur.getLong(PROJECTION_BEGIN_INDEX);
    title = cur.getString(PROJECTION_TITLE_INDEX);

    // Do something with the values.
    ...
}

I would genuinely rather do this :

// Get the field values
long eventID = cur.getLong(PROJECTION_ID_INDEX);
long beginVal = cur.getLong(PROJECTION_BEGIN_INDEX);
String title = cur.getString(PROJECTION_TITLE_INDEX);

I assume Google developpers are somehow really qualified, so I wonder, since we are in the very same scope : what are the pros and cons of declaring the first way instead of the second ?

Upvotes: 3

Views: 2491

Answers (1)

Bathsheba
Bathsheba

Reputation: 234705

It's a question of style. I don't initialise unnecessarily for two reasons:

  1. Doing so clobbers an extra check a Java compiler will give you as compilation will not be successful if a variable that is not initialised on all control paths is encountered.

  2. It gives the impression that null is an acceptable value for the reference, which often it isn't.

Upvotes: 9

Related Questions