Java Does Not Equal (!=) Not Working? [duplicate]

It is possible that the != operator is not working as expected in your Java code because you are using it to compare object references, rather than the contents of the objects themselves.

In Java, the == operator compares object references to see if they refer to the same object in memory. If you want to compare the contents of two objects, you need to use the equals method.

For example, consider the following code:

String s1 = new String("hello");
String s2 = new String("hello");

if (s1 != s2) {
  System.out.println("s1 and s2 are not equal");
}

This code will print "s1 and s2 are not equal" because s1 and s2 are different object references, even though they have the same contents.

To compare the contents of the objects, you can use the equals method like this:

if (!s1.equals(s2)) {
  System.out.println("s1 and s2 are not equal");
}

This will correctly determine that s1 and s2 are equal, because they have the same contents.

I hope this helps! Let me know if you have any other questions.