-2

A code below returns me an error and it won't connect to a SQlite db.

public class CardDatabase {

    private String dataBaseName;

    public CardDatabase(String dataBaseName) {
        this.dataBaseName = dataBaseName;
    }

    String databaseUrl = "jdbc:sqlite:./" + dataBaseName; // Value 'dataBaseName' is always 'null' 
    SQLiteDataSource dataSource = new SQLiteDataSource();

Although the code below works great.

public class CardDatabase {

    private String dataBaseName;

    public CardDatabase(String dataBaseName) {
        this.dataBaseName = dataBaseName;
    }
    
    SQLiteDataSource dataSource = new SQLiteDataSource();
    String databaseUrl = "jdbc:sqlite:./" + dataBaseName; // swaped two lines

Can you help me realize what's the difference between those two codes and why the first one won't compile?

1 Answers1

1

String databaseUrl = "jdbc:sqlite:./" + dataBaseName; is initialized before the constructor is executed.

Meaning it will always use null because dataBaseName is not yet initialized.

But you can move the initialization into the constructor. It is also preferred to place the fields before the constructor, and if you never reassign them, you can make them final, meaning the can't be overwritten:

public class CardDatabase {

    private final SQLiteDataSource dataSource = new SQLiteDataSource();
    private final String dataBaseName;
    private final String databaseUrl;

    public CardDatabase(String dataBaseName) {
        this.dataBaseName = dataBaseName;
        this.databaseUrl = "jdbc:sqlite:./" + dataBaseName;
    }
}

Regarding the error you're receiving: It can simply be that your IDE is not analysing your code thouroughly enough, that it can check that dataBaseName is still null after the line SQLiteDataSource dataSource = new SQLiteDataSource();

Lino
  • 19,604
  • 6
  • 47
  • 65