To compare strings for their content equality we must use the String.equals()
method. This method ensures that it will compare the content of both string instead of the object reference of the both string. This method returns true
if both string in comparison have the same content.
Do not, never, use the ==
operator to compare string for its content. The ==
operator check for object reference equality, it returns true
only if both objects point to the same reference. This operator returns false
if the object doesn’t point to the same references.
package org.kodejava.lang;
public class StringEquals {
public static void main(String[] args) {
String s1 = "Hello World";
String s2 = new String("Hello World");
// This is good!
if (s1.equals(s2)) {
System.out.println("1. Both strings are equals.");
} else {
System.out.println("1. Both strings are not equals.");
}
// This is bad!
if (s1 == s2) {
System.out.println("2. Both strings are equals.");
} else {
System.out.println("2. Both strings are not equals.");
}
}
}
In the example above we deliberately create an instance of s2
string using the new
operator to make sure that we have a different object reference. When you run the program it will give you the following result:
1. Both strings are equals.
2. Both strings are not equals.
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023