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.
Invalid problem or permissions
Solution
public boolean stringsTheSame( String a, String b ) {
return a.equals(b);
}
In this series
Want to stay in touch and keep up to date with the latest posts @ CompSci.rocks?