How to Compare 2 Strings in Java?

Use `str1.equals(str2)` for case-sensitive content comparison

Use `str1.equalsIgnoreCase(str2)` for case-insensitive content comparison

Use `str1.compareTo(str2)` to compare lexicographically

Use `str1.compareToIgnoreCase(str2)` to compare lexicographically without case sensitivity

Use `==` only to compare object references, not string contents

Use `Objects.equals(str1, str2)` to safely compare when either string may be `null`

Use `String.valueOf(str1).equals(String.valueOf(str2))` if you need null-safe conversion before comparing

Use `str1.contentEquals(str2)` to compare against a `StringBuilder` or `StringBuffer`

Use `Arrays.equals(str1.toCharArray(), str2.toCharArray())` to compare character arrays derived from strings

Use `str1.regionMatches(…)` to compare specific parts of strings

Suggested for You

Trending Today