mitchyb mitchyb - 3 months ago 22
Java Question

Explanation to why connection = null in JDBC

Every time I check out a tutorial for JDBC programmers seem to set the connection as null

Connection conn = null;


and I can't figure out why. Can someone clarify this for me?

Answer

Usually, it's so the finally block can include a check like

} finally {
    // ...
    if (conn != null) {
        try {
            conn.close();
        } catch (Exception e) {
        }
    }
}

Without the default initialization to null, you'd get an error that conn might not have been initialized.