Why am I getting a Null Pointer Exception from this Java code? [closed]

Although this question may have been solved, here's a little bit on how to go about debugging given an stack trace.

In this case, the stack trace is the following:

Exception in thread "main" java.lang.NullPointerException
    at test.DBCommunicator.getStatment(DBCommunicator.java:107)
    at test.database.DBManager.getUsernameforID(DBManager.java:359)
    at dbtestdrive.Main.main(Main.java:25)

What this shows is that in the test.DBCommunicator.getStatment method, a NullPointerException was thrown at the location of line 107 of DBCommunicator.java.

Furthermore, the getStatment method was called from line 358 of DBManager.java which is in the DBManager.getUsernameforID method.

Therefore, the first place that should be checked is what is going on at line 107 of DBCommunicator.java.

Although there are no line numbers in the code snippet given, one can presume that a NullPointerException occurred in the following line:

ps = (PreparedStatement) connection.prepareStatement(st);

There's one thing that is fairly common about NullPointerExceptions -- they generally arise when method calls are performed on an null reference. Invoking a method on an object that doesn't exist will throw a NullPointerException.

In the above code, one can expect that the connection variable is actually null, rather than having a Connection.

This should lead to trying to track down why the connection variable is null rather than having a valid connection to the database that is initialized.

It is probably because your query is failing, try changing it to:

String statment = "SELECT USERNAME  FROM `BENUTZER` WHERE `ID` = ?";

Your original query had a trailing semi-colon, which is illegal. This could have caused a nullpointerexception to be thrown up at a later stage, I would advise you to post the contents of your exception.



Should be:


You're misspelling 'statement' as 'statment', which is fine for a variable name, but not when referring to a method :)

//Ending ";" inside the string, is not neccessary.
String statment = "SELECT USERNAME  FROM `BENUTZER` WHERE `ID` = ? ;";

Instead of:

PreparedStatement ps = dbCommunicator.getStatment(statment);

PreparedStatement ps = dbCommunicator.prepareStatement(statment);

That's what I have using oracle.