Equals Method

Think back to the first post in this series when we talked about how Java stores string variables. Specifically how it’s not really storing the string in the variable but the memory address of where it can find the string.

For primitive variables you can use two equals signs to compare values like this.

int x = 3;
int y = 3;
System.out.println( x == y );

Catch is, this won’t work with Strings. Or really with any non primitive variables. And it’s because Java would be comparing memory addresses.

What to do?

All objects in Java have an equals method that lets you compare the current object with another instance of the same type. And since a string is an object, it has that method.

It’s up to the creator of the class to implement the equals method to compare the two instances. And equals on a string does exactly what you would think. It compares each character, and if they match then they’re equal.

But == works (sometimes)

Yeah, this is where it gets confusing for my students. Sometimes they get the right answer using == and not using the equals method.

What’s happening is that Java is trying to be efficient and stores strings in a table. When two instances contain the same characters Java may point them to the same spot in memory and the variables would be equal. But there’s not guarantee that it does this, and you shouldn’t bank on it.

How To

In the following code we’re going to create two strings, stringOne and stringTwo and then print out the comparison between the two.

String stringOne = "Chicken";
String stringTwo = "Chicken";
System.out.println( stringOne.equals( stringTwo ) ); 

This code would print out true because the two strings contain the exact same characters.

A couple of things to note.

First, the comparison is case sensitive so Chicken and cHICKEN would not be considered the same values.

And it really doesn’t matter which way you do the comparison. In the above code stringOne.equals(stringTwo)) is essentially interchangeable with stringTwo.equals(stringOne)).

Code Time

This time we’re implementing a method that returns true if two strings contain exactly the same characters or false if they do not.


Solution
public boolean stringsTheSame( String a, String b ) {
    return a.equals(b); 
}

In this series

A quick, short introduction to strings in Java.
You can't always work with string literals. You need variables.
Concatenation is the fancy word for combining multiple strings.
Built in method to see if two strings are the same.
Need to know how many characters are in a string? There's a method for that.
indexOf / lastIndexOf
CompSci.rocks Newsletter

Want to stay in touch and keep up to date with the latest posts @ CompSci.rocks?

Leave a Reply

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