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()) ... 
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist