Skip to content

Instantly share code, notes, and snippets.

@jovemfelix
Last active October 30, 2020 20:22
Show Gist options
  • Select an option

  • Save jovemfelix/ecd11357d9d7b3e779e4b1c950cb7cd3 to your computer and use it in GitHub Desktop.

Select an option

Save jovemfelix/ecd11357d9d7b3e779e4b1c950cb7cd3 to your computer and use it in GitHub Desktop.
Best Practices of Equals Testing in Java
import java.util.Objects;
class Scratch {
public static void main(String[] args) {
String s = null;
try {
if (!s.equals("XXX")) {
System.out.println("[WRONG-TESTING] NOT EXECUTED!");
}
} catch (NullPointerException e) {
System.out.println("[WRONG-TESTING] LEAD TO NPE!");
}
if (!"XXX".equals(s)) {
System.out.println("[BEST_PRACTICE-01] test with constant first!");
}
if (!Objects.equals("XXX", s)) { // using equals utility
System.out.println("[BEST_PRACTICE-02] doesn't matter the object orders!");
}
if (!Objects.equals(s, "XXX")) { // using equals utility
System.out.println("[BEST_PRACTICE-02] doesn't matter the object orders!");
}
if (Objects.equals(s, null)) { // using equals utility
System.out.println("[BEST_PRACTICE-02] NULL == NULL!");
}
}
}
/* ##### OUTPUT is:
[WRONG-TESTING] LEAD TO NPE!
[BEST_PRACTICE-01] test with constant first!
[BEST_PRACTICE-02] doesn't matter the object orders!
[BEST_PRACTICE-02] doesn't matter the object orders!
[BEST_PRACTICE-02] NULL == NULL!
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment