1. Home
Java

Step by Step Java Tutorial Concepts - From Beginner to Pro

Learn Java programming from basics to advanced concepts with our comprehensive tutorials. Start from scratch and elevate your skills to expert level.

  • 192 Lessons
  • 32 Hours
right-top-arrow

Tutorial Playlist

191 Lessons
138

String Comparison in Java

Updated on 21/05/20244,661 Views

Overview

Have you ever wondered how you register for different websites and it has two sections for your password? One says “New Password'' and the other one says “Confirm Password”. Have you ever faced a prompt saying “Passwords do not match”? That is what String comparison is all about. Let’s delve into this blog and see what String comparison in Java is all about.

What is String Comparison in Java?

String comparison in Java is basically comparing two Strings to check whether they match or not. As Strings are objects, it require methods or operators to check whether they are identical or not.

We will delve into comparing Strings in Java by using different methods such as equals(), equalsIgnoreCase(), compareTo(), compareToIgnoreCase(), and the == operator. We shall also type in a code that will compare two strings manually using the for loop and conditional statements. Keep reading to find out more about string comparison in Java.

Ways to Compare Two Strings in Java

There are multiple ways through which you can compare Strings in Java. Let’s get into the inbuilt methods that Java provides users to compare Strings in the section below:

The equals() Method

Code:

public class upGradTutorials{
public static void main(String[] args) {
String str1 = "Hello";
        String str2 = "hello";
       boolean areEqual = str1.equals(str2); 
        System.out.println(areEqual);
    }
}

Output:

false

In the example above, we are taking two Strings, str1 containing Hello and str2 containing Hello and hello. Note that these two Strings aren’t the same in their casing. We then declare a boolean variable areEqual, and then compare both strings using the equals() function.

This boolean variable will return either a true value if both the Strings are exactly identical or false if they are not. We then print the value of the boolean variable areEqual and it returns a false value as str1 and str2 are not identical.

The equalsIgnoreCase() Method

In the above string comparison in Java program, we saw that the strings were the same but had different casing. The equalsIgnoreCase method compares two strings and ignores if there’s a difference in the casing.

Below is the code for comparing two Strings in Java using the equalsIgnoreCase() method:

Code:

public class upGradTutorials{
public static void main(String[] args) {
String str1 = "Hello";
        String str2 = "hello";
       boolean areEqual = str1.equalsIgnoreCase(str2); 
        System.out.println(areEqual);
    }
}

Output:

true

In the code above, we do the same that we did while using the equals() method. But we use the equalsIgnoreCase() so the output is true as it is the same String, but the casing is different. The code compares two strings, str1, and str2.

This method checks if the strings are equal, ignoring the case of the characters. In this case, str1 is assigned the value "Hello", and str2 is assigned the value "hello". Despite the difference in the case, the equalsIgnoreCase() method considers them equal and returns true. The result is stored in the areEqual variable. Finally, the value of areEqual is printed using System.out.println(), which will output true.

The compareTo() method

The compareTo method can also be used to compare Strings in Java. The only difference between equals() and compareTo() methods is that the equals() method returns a boolean value, i.e., true or false, while the compareTo() method returns an integer value, i.e., positive/ negative, or 0 and it compares the strings lexicographically.

Below is the code for comparing two strings in Java using the compareTo() method:

Code:

public class upGradTutorials{
public static void main(String[] args) {
String str1 = "apple";
        String str2 = "banana";
       int result = str1.compareTo(str2); 
        System.out.println(result);
    }
}

Output:

-1

In the code above, we take two Strings str1 and str2. We set str1 as apple and str2 as banana. We declare an integer call result. We then use the compareTo() function to compare str1 to str2 and then print the result using System.out.println(). This returns the value of -1 as the strings do not match.

Do it yourself: Try declaring the value of str2 as apple and see what the result is.

The compareToIgnoreCase() method

This method is just like the equalsIgnoreCase method. So we take two strings str1, str2, containing Apple and apple as values and run them through the compareToIgnoreCase() method. We will get a result of 0 as the method does not take casing into consideration and determines that both the strings are the same, i.e., returns a true value.

Code:

public class upGradTutorials{
public static void main(String[] args) {
String str1 = "Apple";
        String str2 = "apple";
        int result = str1.compareToIgnoreCase(str2); 
        System.out.println(result);
    }
}

Output:

0

First, two string variables are declared: str1 and str2. str1 is assigned the value "Apple," and str2 is assigned the value "apple". The compareToIgnoreCase() method then performs a lexicographic comparison of the strings, considering the Unicode values of the characters, but without distinguishing between uppercase and lowercase letters. It returns an integer value that represents the comparison result.

If the result is less than 0, it means str1 comes before str2 in lexicographical order. If the result is greater than 0, it means str1 comes after str2. If the result is 0, it means both strings are equal. The result of the comparison is stored in the result variable. Finally, the System.out.println() statement is used to print the value of result.

Using the ‘==’ operator

There is another way to perform string comparison in Java, and that is by using the == operator. The == operator Checks whether two strings are in the same memory location or not. This operator is not used to check the content equality but to see whether they refer to the same location in memory.

Below is the code to compare two strings using the == operator:

Code:

public class upGradTutorials{
public static void main(String[] args) {
String str1 = "Hello";
        String str2 = "Hello";
        boolean areEqual = (str1 == str2);
        System.out.println(areEqual);
    }
}

Output:

true

In the code above, we take two strings str1 and str2, having the same value, Hello. We then use the == operator to check whether both the strings point to the same location in memory or not. Since they do, we get an output of true as areEqual is a boolean variable.

Compare two Strings using a custom function

Code:

public class upGradTutorials{
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "Hello";
        boolean areEqual = customCompare(str1, str2);
        System.out.println(areEqual);
    }
    public static boolean customCompare(String str1, String str2) {
        if (str1.length() != str2.length()) {
            return false;
        }
        for (int i = 0; i < str1.length(); i++) {
            char ch1 = str1.charAt(i); 
            char ch2 = str2.charAt(i);
            
            if (ch1 != ch2) {
                return false; 
            }
        }
        return true;
    }
}

Output:

true

In the example above, we have a function that performs the same as the equals() method in Java. We set str1 and str2 to the same value Hello, and pass it through a function customCompare. This function customCompare returns a boolean value that we store into the variable areEqual and then print the result.

The customCompare function takes two strings as parameters and checks whether both strings have the same length. It returns a false value if the strings do not have the same length. If they are of the same length, a for loop is used to loop through the string’s length - 1 as the index of a string starts from 0 and ends length-1 of the string.

A charAt() function is then used to take each character out of both the strings and then compare each character one by one. If one character does not match, then the customCompare() function returns a false value. Otherwise, it returns a true value.

This is how the equals() function works at the most basic level and can be tweaked for string comparison in whatever way the coder deems fit.

Conclusion

String comparison has a lot of real-world applications starting from user authentication, the ‘Find and replace’ function, spell checkers, and lookups in dictionaries.
String comparison also makes its way into more complex applications such as the Boyer-Moore or Knuth-Morris-Pratt algorithms, DNA sequencing, version control systems, and more.

FAQs

1. How can I compare two Strings in Java having leading or trailing whitespaces?

You can use the trim() function to delete any leading or trailing whitespaces in the String and then use the equals() or compareTo() function to compare the two Strings.

2. Can I perform a numeric comparison of Strings in Java?

If you take a number as input in a string variable then you have to use the Integer.parseInt() function and then pass the String variable in it as a parameter. Once you do that, the number gets converted into an Integer data-type from a String- data type and you can use ‘>, <, ==, >=, <=’ to compare them.

3. What do you mean by lexicographically comparing two strings?

Lexicographic comparison is basically comparing two strings according to the alphabetical sequence of their characters. So each character in a string is compared sequentially from left to right in alphabetical order.

Pavan

PAVAN VADAPALLI

Director of Engineering

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working … Read More

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...