Search code examples
javamysqljdbcpass-by-referencepass-by-value

Are JDBC's Connection and Statement objects pass-by-reference or pass-by-value?


I'm learning to use MySQL at the moment and my instinct for instantiating and initializing my Connection and Statement objects was as following:

public class ProjectDriver {
    public static void main(String[] args)
    {
        Connection conn = null;
        Statement stmt = null;
        Initializer.sqlInitialize(conn,stmt);
    ...
    }
...
}

sqlInitialize:

public static void sqlInitialize(Connection conn, Statement stmt) {
    try {
        conn = DriverManager.getConnection(DB_URL, USER, PASS);
        stmt = conn.createStatement();
    } 
    catch (SQLException se) {
        se.printStackTrace();
    } 
    catch (Exception e) {
        e.printStackTrace();
    }
...
}

as well as an sqlClose method to close the Connection and Statement later on.

My instinct says that the Connection and Statement objects in the ProjectDriver should be properly initialized to their respective forms after the sqlInitialize method has been run, but that most certainly isn't the case. Eclipse has a null-pointer access warning in the IDE, and a NullPointerException error is thrown upon trying to run stmt.ExecuteUpdate(sql);.

I'm pretty sure this is a stupid question, but I can't figure out how to Google (or inquire of StackOverflow) why this is happening. I know that the code I provided isn't really the proper way to do what I'm doing, but I'm curious as to why this is happening. My understanding of pass-by-reference vs. pass-by-value in Java is that all primitives are pass-by-value, and that all Objects are pass-by-reference. Shouldn't modifications made to the Connection and Statement objects in another class remain, even after returning to the main?


Solution

  • Java "passes references by value".

    If you assign a parameter within a method, then that doesn't affect the caller. However, if you modify the object pointed to by the parameter, then every variable that refers to that object will see the modification (within the limitations of the memory model if multl-threaded).

    For handling resources, such as JDBC Connection and Statement you will generally want to use the Execute Around idiom.