Comparing Strings

boolean result = str1.equals(str2);
											boolean result2 = str1.equalsIgnoreCase(str2);

The value of result and result2 will be true if the strings contain the same content. If the strings contain different content, the value of result and result2 will be false. The first method, equals(), is case sensitive. The second method, equalsIgnoreCase(), will ignore the case of the strings and return true if the content is the same regardless of case.

String comparison is a common source of bugs for novice Java programmers. A novice programmer will often attempt to compare strings using the comparison operator ==. When used with Strings, the comparison operator == compares object references, not the contents of the object. Because of this, ...

Get Java™ Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.