Hire QA – Specialized in QA Recruitment, Technical Interviews and Testing Solutions

How to compare two Strings in java program?

Category: Java

Below are 5 ways to compare two Strings in Java:

  1. Using user-defined function : Define a function to compare values with following conditions :
    • if (string1 > string2) it returns a positive value.
    • if both the strings are equal lexicographically
      i.e.(string1 == string2) it returns 0.
    • if (string1 < string2) it returns a negative value.
  2. Using String.equals()
    • str1.equals(str2);
  3. Using String.equalsIgnoreCase()
    • str2.equalsIgnoreCase(str1);
  4. Using Objects.equals() : Objects.equals(Object a, Object b)
    • Objects.equals(string1, string2);
  5. Using String.compareTo()
    • int str1.compareTo(String str2);

Leave a Reply

Your email address will not be published. Required fields are marked *