Which method is used to compare two strings?

Which method is used to compare two strings?

Academy

Data Science

Neovarsity

Topics

Explore

CoursesEvents

Search for Courses, Topics

Free Courses

Sign in

Sign in

Got suggestions? We would love to hear your feedback.

Your feedback is important to help us improve

CloseSubmit

A Free learning platform

made with     by  

Download the App!

Explore Scaler

  • Academy
  • Data Science & ML
  • Neovarsity

Explore Topics

  • Courses
  • Challenges
  • Contest
  • Reading Tracks
  • Articles
  • Events

Resources

  • About Us
  • Blog
  • Careers
  • Review

Privacy Policy

Terms of Use

Contact Us

Copyright 2022 InterviewBit Technologies Pvt. Ltd.  

All Rights Reserved.

Which method is used to compare two strings?
Get a Free personalized Career Roadmap from

Which method is used to compare two strings?

There are three ways to compare strings in Java. The Java equals() method compares two string objects, the equality operator == compares two strings, and the compareTo() method returns the number difference between two strings.


String comparison is a crucial part of working with strings in Java. For instance, if you’re building an app for a coffee shop that checks who ordered which drink, you may want to compare the name of the customer with the one you have on-file.

Which method is used to compare two strings?

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest
First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

This tutorial will discuss, with reference and examples, how to compare strings in Java. We will discuss the three main options used to compare strings, and explore the limitations of the == operator when comparing strings in Java.

By the end of reading this tutorial, you’ll be an expert at comparing strings in Java.

Java Strings

Strings are used for storing text-based data in programming. Strings in Java are defined as a sequence of characters surrounded by double quotation marks. Here’s an example of a string in Java:

In this example, we declare a string called day which stores the value Monday.

But what if we wanted to compare this string with another string? There are three main methods which can be used to compare strings in Java. These are:

  • Using the == operator
  • Using the equals() and equalsIgnoreCase() methods
  • Using the compareTo() and compareToIgnoreCase() methods

Compare Strings Using ==

The == operator, known as the equality operator, is used to compare two strings in Java.

Suppose we are operating a coffee shop and we want to compare whether a customer’s name matches the one we have associated with a particular order. We could compare these names using the following code:

public class CompareNames {
	public static void main(String[] args) {
		String orderName = "James";
		String customerName = "James";

		if (orderName == customerName) {
			System.out.println("The customer's name matches the order name.");
		} else {
			System.out.println("The customer's name does not match the order name.");
		}
	}
}

Our code returns:

The customer's name matches the order name.

Let’s break down our code. First, we declare a class called CompareNames which stores the code for our program. We then declare a variable called orderName which stores the name associated with a particular order, and a variable called customerName which stores the name of the customer who is looking for their drink.

We then use an if statement and the equality operator to compare the value of orderName and the value of customerName. Here’s the line of code which performs this comparison:

if (orderName == customerName)

If the values stored within orderName and customerName are equal—which they are in this case—the message The customer’s name matches the order name. is printed to the console. Otherwise, the message The customer’s name does not match the order name. is printed to the console.

Compare String Objects Using ==

In the above example, we declared two strings and used the == operator to compare them. However, this approach does not work when you are comparing two string objects.

Here’s what happens if we try to compare two string objects using the == operator:

public class CompareNames {
	public static void main(String[] args) {
		String orderName = new String("James");
		String customerName = new String("James");

		if (orderName == customerName) {
			System.out.println("The customer's name matches the order name.");
		} else {
			System.out.println("The customer's name does not match the order name.");
		}
	}
}

Our code returns:

The customer's name does not match the order name.

Even though we assign the string value James to both string objects, the program does not treat them the same. This is because the program will not compare the value of the strings, rather the objects themselves.

In our code, we have declared two string objects, each of which have different object references. So, when we try to compare them using ==, our program treats them as different objects.

Compare Strings Using equals()

The Java string equals() method compares two strings in Java.

Let’s return to the coffee shop example. Suppose we want to compare the name we have associated with a coffee order and the name of a customer. We could do so using this code:

public class CompareNames {
	public static void main(String[] ags) {
		String orderName = "James";
		String customerName = "James";

		bool areEqual = orderName.equals(customerName);
		
if (areEqual) {
			System.out.println("The customer's name matches the order name.");
		} else {
			System.out.println("The customer's name does not match the order name.");
		}
	}
}

Our code returns:

The customer's name matches the order name.

In this example we use the equals() method to compare the values of orderName and customerName.

We then assign the value of the equals() method to a boolean called areEqual. If areEqual returns true, a message stating The customer’s name matches the order name. is printed to the console; otherwise, if areEqual returns false, a message stating The customer’s name does not match the order name. is printed to the console. In this case, orderName and customerName is equal, so areEqual is equal to true.

You can use the equalsIgnoreCase() method in the same way as equals() to compare strings. The only difference between equals() and equalsIgnoreCase() is that the latter compares two strings irrespective of their case, whereas the former is case sensitive.

If you’re interested in learning more about the string equals() method, read our tutorial on the topic.

Compare Strings Using compareTo()

The Java string compareTo() method is used to compare two strings lexicographically.

The compareTo() method compares the Unicode value of each character in the two strings you are comparing. compareTo() returns 0 if the string is equal to the other string, less than 0 if the string has fewer characters than the other string, and greater than 0 if the string has more characters than the other string. 

Which method is used to compare two strings?

"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"

Venus, Software Engineer at Rockbot

Suppose we wanted to compare the names of our coffee shop customer and the name we have associated with a drink lexicographically. We could do so using this code:

public class CompareNames {
	public static void main(String[] ags) {
		String orderName = "James";
		String customerName = "Bill";

		int difference = orderName.compareTo(customerName);
		
		System.out.println("Difference: " + difference);
	}
}

Our code returns:

In this example, our code uses compareTo() to compare the value of customerName to the value of orderName. In this case, the value of orderName, James, does not match the value of customerName, Bill.

Because orderName has more characters than customerName, our code returns a value greater than 0, equal to the Unicode differences in our two strings.

In addition, the compareTo() method is case sensitive. If you want to compare strings lexicographically without regard for the cases of the characters in your strings, you can use the compareToIgnoreCase() method. The syntax for the compareTo() and compareToIgnoreCase() method is the same.

Conclusion

Comparing the values stored in two strings is a common operation in Java.

This tutorial discussed how to compare two strings using the equality operator (==), the equals() method, and the compareTo() method. We also discussed the limitations of the equality operator in comparing objects. We also walked through an example of each of these methods in action.

You now have the skills you need to start comparing strings in Java like a professional coder!

Which method is used to compare two strings objects for their equality?

The String. Equals method can easily determine if two strings are the same. This case-sensitive method returns a true or false Boolean value.

Can I use == to compare two strings?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.