String Comparison Methods in Java with Examples

String comparison is a common operation in Java that enables you to determine how two strings are related to each other. Java provides several methods for comparing strings, each serving different use cases. In this blog post, we'll explore the main string comparison methods available in Java, along with examples.

String Comparison Methods in Java 

1. Using equals(Object anObject) 

Compares this string to the specified object. 

Example:

String str1 = "Java";
String str2 = "Java";
boolean result = str1.equals(str2);
// Result: true

2. Using equalsIgnoreCase(String str) 

Compares this string to another string, ignoring case considerations. 

Example:

String str1 = "Java";
String str2 = "java";
boolean result = str1.equalsIgnoreCase(str2);
// Result: true

3. Using regionMatches( ) 

Test if two string regions are equal. 

Example:

String str1 = "Welcome to Java";
boolean result = str1.regionMatches(11, "Java", 0, 4);
// Result: true

4. Using startsWith( ) Method

This method checks if this string starts with the specified prefix. 

Example:

String str = "Java Programming";
boolean result = str.startsWith("Java");
// Result: true

5. Using endsWith( ) Method

This method checks if this string ends with the specified suffix. 

Example:

String str = "Java Programming";
boolean result = str.endsWith("Programming");
// Result: true

6. equals( ) Versus == 

The equals() method compares the content, whereas == compares object references. 

Example:

String str1 = new String("Java");
String str2 = new String("Java");
boolean result1 = str1.equals(str2); // true
boolean result2 = (str1 == str2); // false

7. Using compareTo( ) 

Compares two strings lexicographically. 

Example:

String str1 = "Apple";
String str2 = "Banana";
int result = str1.compareTo(str2);
// Result: -1

8. Using compareToIgnoreCase(String str) 

Compares two strings lexicographically, ignoring case differences. 

Example:

String str1 = "Apple";
String str2 = "apple";
int result = str1.compareToIgnoreCase(str2);
// Result: 0

Summary 

Java provides a wide array of methods for comparing strings, each serving different use cases. By understanding these methods and their specific applications, you can perform complex string comparisons and manipulations with ease. 

Java String Related Posts

Comments