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 build simple search page using ZK and Spring Boot? - March 8, 2023
- How do I calculate days between two dates excluding weekends and holidays? - January 12, 2023
- How do I discover the quarter of a given date? - January 11, 2023