Java String Compare

In this chapter you will learn:

  1. How to compare two String values
  2. How to compare two string value for equality
  3. What are the difference between equals() and ==

Compare two String values

Here are the two methods we can use to compare two String values.

  • int compareTo(String anotherString) compares two strings lexicographically.
  • int compareToIgnoreCase(String str) compares two strings lexicographically, ignoring case differences.

The result of the compareTo(String anotherString) and compareToIgnoreCase(String str) is shown here:

ValueMeaning
Less than zeroThe invoking string is less than str.
Greater than zeroThe invoking string is greater than str.
ZeroThe two strings are equal.
public class Main {
  public static void main(String[] argv) {
    String str = "Demo2s.com";
    String str2 = "demo.com";
    System.out.println(str.compareTo(str2));
    System.out.println(str.compareToIgnoreCase(str2));
/*j  a v  a  2s.com*/
  }
}

The output:

compareToIgnoreCase(String str) returns the same results as compareTo( ). It only ignores the case differences.

public class Main {
//from   j  a  v  a  2 s  . co m
  public static void main(String args[]) {
    System.out.println("A".compareToIgnoreCase("a"));
  }
}

The output:

Compare two string value for equality

The following two methods compare string value for equality.

  • boolean equals(Object anObject) compares this string to the specified object.
  • boolean equalsIgnoreCase(String anotherString) compares this String to another String, ignoring case considerations.
public class MainClass {
  public static void main(String args[]) {
  String s1 = "Hello";
  String s2 = "Hello";
  String s3 = "Goodbye";
  String s4 = "HELLO";
  System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
  System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3));
  System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4));
  }//from   j  a  v a2 s .  co m
}

The following code checks the length of a string, then gets the fourth char out of the string object and compares these two string objects.

public class Main {
  public static void main(String args[]) {
    String strOb1 = "demo2s.com";
    String strOb2 = "demo2s.com";
    String strOb3 = strOb1;/*from  jav  a  2 s .  co m*/

    System.out.println("Length of strOb1: " + strOb1.length());
    System.out.println("Char at index 3 in strOb1: " + strOb1.charAt(3));

    if (strOb1.equals(strOb2))
      System.out.println("strOb1 == strOb2");
    else
      System.out.println("strOb1 != strOb2");

    if (strOb1.equals(strOb3))
      System.out.println("strOb1 == strOb3");
    else
      System.out.println("strOb1 != strOb3");
  }
}

This program generates the following output:

The comparison is case-sensitive.

public class Main {
  public static void main(String args[]) {
    String s1 = "Hello";
    String s2 = "Hello";
    String s3 = "Good-bye";
    String s4 = "HELLO";
    System.out.println(s1 + " equals " + s2 + " -> " +
// j a v a2s .  co m
    s1.equals(s2));
    System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3));
    System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4));
    System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " 
                          + s1.equalsIgnoreCase(s4));
  }
}

The output:

To compare igoring case, call equalsIgnoreCase(). It has this general form:

boolean equalsIgnoreCase(String str)

str is the String object being compared with the invoking String object. Here is an example that demonstrates equals( ) and equalsIgnoreCase( ):

public class Main {
  public static void main(String args[]) {
    String s1 = "Hello";
    String s2 = "Hello";
    String s3 = "Good-bye";
    String s4 = "HELLO";
    System.out.println(s1 + " equals " + s2 + " -> " +
/*from java2s  .  c  o m*/
    s1.equals(s2));
    System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3));
    System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4));
    System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " 
                        + s1.equalsIgnoreCase(s4));
  }
}

The output from the program is shown here:

equals() vs ==

equals( ) method and the == operator perform two different operations. equals( ) method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance.

The following program shows the differences:

public class Main {
  public static void main(String args[]) {
    String s1 = "demo2s.com";
    String s2 = new String(s1);
/* j  a v a2s  .  co m*/
    System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
    System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
  }
}

Here is the output of the preceding example:

Next chapter...

What you will learn in the next chapter:

  1. How to check if a string contains in another string
  2. How to check if this string ends with the specified suffix
  3. How to test if a string starts with another string
  4. How to search string from start
  5. How to search a string from the end
Home » Java Tutorial » String

String

    Java String type
    Java String Concatenation
    Java String Creation
    Java String Compare
    Java String Search
    Java String and char array
    Java String Conversion
    String trim, length, is empty, and substring
    String replace

StringBuffer

    StringBuffer class
    StringBuffer Insert and Append
    StringBuffer length and capacity
    StringBuffer char operation
    StringBuffer Operations
    Search within StringBuffer
    StringBuffer to String

StringBuilder

    StringBuilder
    StringBuilder insert and append
    StringBuilder length and capacity
    StringBuilder get,delete,set char
    StringBuilder delete, reverse
    StringBuilder search with indexOf and lastIndexOf
    StringBuilder to String

String Format

    Formatter class
    Format Specifier
    Format String and characters
    Format integer value
    Format decimal
    Scientific notation format
    Format octal and hexadecimal value
    Format date and time value
    Escape Formatter
    Minimum Field Width
    Specifying Precision
    Format Flags
    Uppercase Option
    Formatter Argument Index
    Align left and right
    Left and right padding a string

String Format Utilities

    Abbreviate string
    Caplitalize a string
    Uncapitalize a string
    Utility class for right padding
    Left padding
    Centers a String
    Transforms words