Things to watch out for in Java equals

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));//Execution 2
}

Execution 1 throws a java.lang.NullPointerException. The cause of the exception is that I put null in str1 and called the method from the null object. Calling a method from a non-null str2 will no longer raise an exception and will return false.

Writing execution 2 has the advantage that an exception does not occur even if str1 is null, but it has the disadvantage that it is difficult to notice code mistakes if it is implemented without assuming that null will be entered as an abnormal system. I think.

If you are aware of null checking, it may be safer to catch it 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 a constant pool. Character literals appear frequently in programs. However, if you create an instance of String each time, it will consume a lot of memory.

If the same string literal reappears, the reference to the string instance in the memory space for the constant will be "reused". This is a mechanism called a constant pool.

This constant pool is only valid when using string literals. If you explicitly write to create a new instance using the new operator, an instance will be created 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
}

You won't see it in an actual program, but be careful because it's a common trigger in Java Silver.

Part 3 Case-insensitive judgment

You can use the equalsIgnoreCase method to determine equivalence in a case-insensitive manner. However, I think that the frequency of appearance is considerably lower than that of 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

Recommended Posts

Things to watch out for in Java equals
Things to watch out for when creating a framework
Things to watch out for when using Deeplearning4j Kmeans
Watch out for embedded variables in S2Dao
[Java] Things to note about type inference extended in Java 10
I tried to find out what changed in Java 9
[Ransack] Watch out for ransackable_scopes!
Things to be aware of when writing code in Java
Rock-paper-scissors game for beginners in Java
Multithreaded to fit in [Java] template
[For beginners] Run Selenium in Java
How to learn JAVA in 7 days
Log output to file in Java
Understanding equals and hashCode in Java
How to use classes in Java?
How to name variables in Java
Try to implement Yubaba in Java
Settings for SSL debugging in Java
Things to note in conditional expressions
How to concatenate strings in java
[For beginners] Minimum sample to update RecyclerView with DiffUtils in Java
[Note] Java: Is it necessary to override equals for equality judgment?
Things to note for newcomers to write readable code during Java development
How to implement date calculation in Java
How to implement Kalman filter in Java
Multilingual Locale in Java How to use Locale
Try to solve Project Euler in Java
Easy to make Slack Bot in Java
Java reference to understand in the figure
Introduction to java for the first time # 2
[Java] How to compare with equals method
First steps for deep learning in Java
Try to implement n-ary addition in Java
Key points for introducing gRPC in Java
About the procedure for java to work
How to do base conversion in Java
[Java] for Each and sorted in Lambda
Various things like bit flags in Java
Change List <Optional <T >> to Optional <List <T >> in Java
Convert SVG files to PNG files in Java
How to implement coding conventions in Java
How to embed Janus Graph in Java
How to get the date in java
Add footnotes to Word documents in Java
[Java Bronze] 5 problems to keep in mind
[Java] [For beginners] How to insert elements directly in a 2D array
Sample to unzip gz file in Java
Memo for migration from java to kotlin
[For beginners] How to debug in Eclipse
Add SameSite attribute to cookie in Java
For my son who started studying Java with "Introduction to Java" in one hand
[Java] How to test for null with JUnit
Things to be aware of when writing Java
ChatWork4j for using the ChatWork API in Java
Technology for reading Java source code in Eclipse
How to display a web page in Java
Try to create a bulletin board in Java
Solution for NetBeans 8.2 not working in Java 9 environment
I tried to implement deep learning in Java
How to get Class from Element in Java
There seems to be no else-if in java