[Java] Points to be aware of with Java equals

1 minute read

Part 1 null check


public static void main(String[] args) {

String str1 = null;
String str2 = "test";

System.out.println(str1.equals(str2)); //Run 1
System.out.println(str2.equals(str1)); //Run 2
}

Execution 1 causes java.lang.NullPointerException. The cause of the exception is that null was put in str1 and the method was called from the null object. Calling the method from str2 which is not null will not raise an exception and will return false.

The method of writing execution 2 has the advantage that an exception does not occur even if str1 is null, but if it is implemented without assuming null as an abnormal system, it has the disadvantage that it is hard to notice a code mistake. I think.

If you are aware of null checks, it may be safer to catch them with exception handling.

public static void main(String[] args) {

String str1 = null;
String str2 = "test2";

try {
System.out.println(str1.equals(str2));
}catch(NullPointerException ex) {
System.out.println("Exception catch");
}
}

Part 2 Constant Pool


public static void main(String[] args) {

String str1 = "test1";
String str2 = "test1";

System.out.println(str1.equals(str2)); //Result 1
System.out.println(str1 == str2); // result 2
}

Result 1 is of course true, but what about result 2? In conclusion, result 2 is also true.

This is because there is a mechanism called constant pool. Character literals often appear in programs. However, creating a String instance each time would consume a large amount of memory.

If the same string literal reappears, it will “reuse” references to the string instance in the constant’s memory space. This is a mechanism called constant pool.

This constant pool is valid only when using string literals. If you explicitly use the new operator to create a new instance, it will create an instance each time and each variable will have a different reference.

public static void main(String[] args) {

    String str1 = new String("test");
    String str2 = "test";

    System.out.println(str1.equals(str2)); //true
    System.out.println(str1 == str2); //false
}

First of all, you won’t see it in an actual program, but be careful because it is a common trigger in Java Silver.

Part 3 Case-insensitive judgment

The equalsIgnoreCase method can be used to determine equivalence without regard to case. However, I think it appears much less frequently than equals.


public static void main(String[] args) {

    String str1 = "abc";
    String str2 = "ABC";

    System.out.println(str1.equals(str2)); //false
    System.out.println(str1.equalsIgnoreCase(str2)); //true
}

that’s all