How to Compare Strings in Java

There are a few different ways to compare strings in java, and it can also be quite confusing for a beginner.
This code example aim to show how to compare strings, consider the following code:

The output from the above code is:

The first if statement is never entered since what we are really doing with the == operator is to compare if the string reference is the same for both strings, i.e. both references are pointing to the same string object.
Since we have created two strings using the string constructor (new String()) there are two different string instances existing in memory, and two references pointing to each one.
Had we not used the string constructor, the JVM would have used the same string object for both references, consider this:

Now the if statement would have been entered since the Java Virtual Machine would use the same string in memory for both s1 and s2 since we are not explicitly telling it to create a new one using the string constructor.
The methods equals() and compareTo() methods of the String class doesn’t care if the references are pointing to the same string object or not, they’re simply comparing the values.

Search for more Java info on this site here:
Custom Search

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">