简体   繁体   中英

Why the retrieved result set string doesn't work with the .equals()

I'm retrieving some information from a database and I want to check if the value is null. Although the string retrieved from the database is "null" the equals() returns false.

I tried trim(), just in case there were any spaces in the retrieved string

     String code = product.retrieveCode();
            System.out.println("the code is :"+ code);

            if (code.equals("null")==true){  
                // do this 
            }
            else{
                //   do that
            }    

Please let it be noted that the database doesn't have any data stored.

As pointed out by 'Eran', the value in code is probably a null reference. Do,

if (code == null)

instead of

if (code.equals("null")==true)

This likely occurs because the rs object returns null when you call it's getString() method. ResultSet will return null when the column value is SQL NULL. ( Reference )

your logic and syntax is correct.In this case here your database value is probably assigning null value to code and you are checking whether a string of "null" is equal to code. This will give error as it is null reference. Make sure that you are getting a "null" else if its empty just check equals case withe whitespace

It prints Yes. so I don't think java doing anything wrong

String code = "null";
if (code.equals("null")){  
     System.out.println("Yes");
} else{
   //   do that
}

I think it is a null reference. Please do the below code.

if (code==null){  
   System.out.println("Yes");
} else{
       //   do that
}

1.

code cannot be null as code.equals() would have thrown a NullPointerException because you would call a method from null -> something not existing.

2.

.equals() is case senetive, most databanks store null as NULL , so use code.equalsIgnoreCase("null") .

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