I have a method that takes a string value as a parameter and then checks if that string value exists in the database! The method should return true if the string value already exist and false otherwise! Before i run the method i get a compilation error ” missing return statement”! Does anyone spot an error in the code below ?
public boolean checkID(String sid)
{
try
{
String sessionID = null;
if(dBConnection.connect())
{
Connection con = dBConnection.getConnection();
String query = "SELECT sidvalue FROM sessionid where tokenvalue='" + sid + "'";
Statement pstmt = con.createStatement();
ResultSet resultset = pstmt.executeQuery(query);
while (resultset.next())
{
sessionID = resultset.getString(1);
if(sid.equalsIgnoreCase(sessionID))
{
return true;
}
else
{
return false;
}
}
dBConnection.disconnect();
}//End of If statement
}//End of Try block
catch (Exception e)
{
System.out.println(e);
return false;
}
}//End of method
What if the execution doesn’t pass to the if statement and/or while loop? There is no return value for such cases. Use a boolean variable or
falsevalue to return. Just add areturn false;statement after this linedBConnection.disconnect();, i.e. after the while loop inside the if statement of your try block, it will be done.By the way, I suggest you to use database disconnection statement in a
finallyclause, not inside try block. It’s probable thatdBConnection.disconnect();will not be executed if your method returns any value inside the while loop. Move this linedBConnection.disconnect();to a finally block just after the catch block like this: