The equals() method must be used instead of ==.
example:
public class Main {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "hello";
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
}
}
On the surface, the comparison of two strings with == and equals() is true, but in fact it is just that the Java compiler will automatically put all the same strings as an object in the constant pool during compilation . Naturally, the references of s1 and s2 are the same.
Therefore, this == comparison returns true is purely coincidental. Put another way, == comparison will fail:
public class Main { public static void main(String[] args) { String s1 = "hello"; String s2 = "HELLO".toLowerCase(); System.out.println(s1 == s2); System.out.println (s1.equals(s2)); } } To ignore case comparison, use equalsIgnoreCase() method.