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 get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024