简体   繁体   中英

String Comparison not working in Java

Here is my code : Why is the if ((rs.getString("order_status")) != ordstat) not working?

String sql = "select order_id, order_dt, order_status, prod_name from orders where user_id = '"+user+"'";
try{
s = con.createStatement();
rs = s.executeQuery(sql);
String ordstat = "Pending";
%>
<%
while( rs.next() ){
    if ((rs.getString("order_status")) != ordstat){
%>
<div align="center">
    <table border="1" cellpadding="5">
        <tr>
             <th>Select</th>
            <th>Order ID</th>
            <th>Name</th>
            <th>Date</th>
            <th>Status</th>
        </tr>
            <tr>
             <form action = 'deleteorders' >
                <td><input type="checkbox"/></td>
                <td><%= rs.getString("order_id") %></td>
                <td><%= rs.getString("prod_name") %></td>
                <td><%= rs.getString("order_dt") %></td>
                <td><%= rs.getString("order_status") %></td>

<%
    }
}
%>
          </form>   
                </tr>   
      </table>
      <br>
      <INPUT TYPE=SUBMIT VALUE="CANCEL">
      </div>
<%

}

Try this , as this is the recommended way of doing it

if (!(rs.getString("order_status")).equals(ordstat))

Note that == compares references of the objects and if you want to compare actual content of strings , use equals() function

In java checking for String using the equality operator ("==") means that you are effectively comparing the address of that String object in memory to another String object. It never compares the contents of the String.

To compare 2 Strings always use .equals method

String x = "Hello";
String y = "World";

if (x.equals(y)) //if the strings are equals
   System.out.println("Equals");

if (!x.equals(y)) //if the strings are not equal
   System.out.println("Not Equal");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM