Checking if a final instance variable has been initialized

java

Solution

`final` variables can only be initialized once. Normally, they must be initialized in the constructor, but if they are `static`, then they need to be initialized when they are defined, like this:

private final static SQLiteDatabase database = new SQLiteDatabase(...);

or, you can initialize it later:

private static SQLiteDatabase database;

`static` variables will be initialized before object constructors are called. So in this case, `database` will always be `null` and since it is `null`, re-initializing it in the object constructor will cause a compile time error.

Problem

I am still learning Java but I am not sure why this is causing compile time error: ``` public class AnswerRepository implements IAnswerRepository { private final static SQLiteDatabase database; public AnswerRepository(Activity activity) { if(database != null) { database = DbOpenHelper.getInstance(activity); } } } ``` I am just trying to check if a final variable has been assigned first before assigning a value to it. But it seems compile time checking doesn't like it. Why is that?

Original source