Question

I know it is sily question but please give me an idea why does below mentioned code throw NullPointerException? An initialization is performed in the next order: static fields/initializator - constructor - local variables. Why do I have an exception if when addInvoiceData() is callled all the static variables(connection and statement) are already initialized? If I connect to DB in the method everything works out. Any comments would be appreciated.

public class DaoClass {

    public DaoClass() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ved_project", "root", "1111");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    static Connection connection;
    static PreparedStatement statement;

    public static void addInvoiceData() {
        try {
            statement = connection.prepareStatement("INSERT INTO invoices(contractor_id, invoice_num, date, amount) VALUES (?, ?, ?, ?)");
            statement.setInt(1, 1);
            statement.setString(2, "RM-2014");
            statement.setString(3, "20140212");
            statement.setFloat(4, 125.12f);
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (statement != null) {statement.close();}
                if (connection != null) {connection.close();}
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        addInvoiceData();
    }
}
Was it helpful?

Solution

Because your constructor is never invoked in the above code. To invoke your constructor, you need

new DaoClass()

somewhere.

Note that initializing statis fields from a constructor or instance method is bad design. static fields belong to the class. A constructor is invoked each time an instance of this class is created. There is no reason to reinitialize a static field each time a constructor is called.

Read http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html for a better understanding of static fields and methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top