Click here to Skip to main content
15,919,613 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Why I still get an output "No" even though a is equal to k?

Java
public void CompareType(String a ) throws Exception {
		// TODO Auto-generated method stub
		String k;
		String sql="Select Type from menu ";
		DatabaseConnection db = new DatabaseConnection();
		Connection  conn =db.getConnection();
		PreparedStatement  ps = conn.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		while (rs.next()) 
        {
			k=rs.getString("Type");
		if(a==k)
		{
			System.out.println("Yes");
		}
		else
		{
			System.out.println("No");
        }
        }
		ps.close();
		rs.close();
		conn.close();
	}
Posted

1 solution

That is a well-know Java weirdness 'feature', try, for instance
Java
public class Str
{
  public static void main(String args[])
  {
    String a = "foo";
    String b = "fo";

    b += "o";

    if ( a == b)
    {
      System.out.println("the strings are ==");
    }
    if ( a.equals(b))
    {
      System.out.println("the strings are equal(s)");
    }
  }
}


If you want (you usually want) to compare the content of the two strings then use the equal method.
 
Share this answer
 
Comments
wseng 22-Aug-15 16:00pm    
Thanks
CPallini 22-Aug-15 16:53pm    
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900