devxlogo

Testing for String Equality

Testing for String Equality

if (name.compareTo("Jerry") == 0) ...if (name == "Jerry") ...if (name.equals("Jerry")) ...if ("".equals(name)) ...

All the above comparisons are correct, but they are not great. The compareTo method is overkill and too diffuse. The == operator tests the object identity, which is not desirable. The equals method is OK, but reversing the constant and variable give you extra security if the name is null.

if ("Jerry".equals(name)) ...if (name.length() == 0) ...if (name.isEmpty()) ... 

devx-admin

Share the Post: