|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
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: |
package com.javadb.examples; public class Main { public static void main(String[] args) { String s1 = new String("abc"); String s2 = new String("abc"); if (s1 == s2) { System.out.println("s1 == s2"); } if (s1.equals(s2)) { System.out.println("s1.equals(s2)"); } if (s1.compareTo(s2) == 0) { System.out.println("s1.compareTo(s2) == 0"); } } } |
| The output from the above code is: |
s1.equals(s2) s1.compareTo(s2) == 0 |
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: |
String s1 = "abc"; String s2 = "abc"; if (s1 == s2) { System.out.println("s1 == s2"); } |
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. |
| Do you know your Java? | |
| Take a Ten-Question-Java-Quiz! | |
Search for code examples on this site
