Hey, I'm having a problem with an if statement. I want to check if variable key and id are the same. They are both strings and when I print them to screen they certainly look the same. However when using them within an if statement it always returns false. Here is my code, I have commented where the statement is not reverting true when it should. Thanks for your help:

<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<%@ include file="connection.jsp" %>


<html>
<head>
<title>Web hosting FAQ</title>
</head>

<body>

<center><h1>Customer area</h1></center>
Frequently asked questions about web hosting: <br />
<%

String key = null;
key = request.getParameter("question"); 

String id = null;
String Question = null;
String Answer = null;
String Updated = null;
String Author = null;


ResultSet columns1 = statement.executeQuery("SELECT * FROM Questions");

 while(columns1.next())
  {
    id = columns1.getString("ID");
    Question = columns1.getString("Question");
    Answer = columns1.getString("Answer");
	Updated = columns1.getString("Timestamp");
	Author = columns1.getString("Author");	

			if (id == key)
		        {
			         out.print("This statement should be true!);
							
			}

%>
<a href="custarea.jsp?question=<%=id %>"><%=Question %></a> <br />
<%
			
			
	} %>

</body>
</html>

The == operator in case of references compares the references and not the values to which they refer. Since both id and key don't refer to the same string instance in memory, it always returns false. What you need here is to use the equals() method to do the same.

But seriously, this is the very basic of Java programming every programmer out there ought to know. I would recommend you go through the basic Java programming tutorials on the official Sun site before diving head first in J2EE.

Comments
Thanks! Your post helped me solve my silly mistakes too...

Okay thanks for you're help but I've just come from a C# background (hence I didn't know the different between == and equals() and I've only been learning the language for a few weeks

Try this. It compares to strings.

if (id.equals(key))

{

out.print("This statement should be true!);

 

}

Yea thanks I figured it out from ur previous post, thanks 4 ur help

This question has already been answered. Start a new discussion instead.