Describe all the string comparison methods available in java with examples.
Answer:-
String Comparison Methods in Java
Java provides several methods to compare String
values. These methods can compare based on content, lexicographical order, or case-insensitive equality.
1. equals(String anotherString)
- Compares content of two strings.
- Case-sensitive.
String s1 = "Java"; String s2 = "Java"; System.out.println(s1.equals(s2)); // true
2. equalsIgnoreCase(String anotherString)
- Compares content ignoring case.
String s1 = "Java"; String s2 = "java"; System.out.println(s1.equalsIgnoreCase(s2)); // true
3. compareTo(String anotherString)
- Lexicographically compares strings.
- Returns:
0
if both are equal,< 0
ifs1 < s2
,> 0
ifs1 > s2
String s1 = "Apple"; String s2 = "Banana"; System.out.println(s1.compareTo(s2)); // Negative value
4. compareToIgnoreCase(String anotherString)
- Same as
compareTo()
but ignores case.
String s1 = "apple"; String s2 = "Apple"; System.out.println(s1.compareToIgnoreCase(s2)); // 0
5. startsWith(String prefix)
- Checks if string starts with the given prefix.
String s = "HelloWorld"; System.out.println(s.startsWith("Hello")); // true
6. endsWith(String suffix)
- Checks if string ends with the given suffix.
String s = "HelloWorld"; System.out.println(s.endsWith("World")); // true
7. contains(CharSequence seq)
- Checks if string contains the given sequence.
String s = "Learning Java"; System.out.println(s.contains("Java")); // true
8. regionMatches(...)
- Compares a specific region (substring) of two strings.
String s1 = "HelloWorld"; String s2 = "World"; System.out.println(s1.regionMatches(5, s2, 0, 5)); // true
9. matches(String regex)
- Compares using regular expressions.
String s = "abc123"; System.out.println(s.matches("[a-z]+\\d+")); // true
Summary Table
Method | Case Sensitive | Purpose |
---|---|---|
equals() | Yes | Content equality |
equalsIgnoreCase() | No | Content equality |
compareTo() | Yes | Lexicographic comparison |
compareToIgnoreCase() | No | Lexicographic comparison |
startsWith() | Yes | Starts with prefix |
endsWith() | Yes | Ends with suffix |
contains() | Yes | Contains sequence |
regionMatches() | Optional | Region-wise comparison |
matches() | Yes | Pattern match using regex |