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 {
	}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 == 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

that's all

Recommended Posts

Things to watch out for in Java equals
Things to watch out for in future Java development
Things to watch out for when creating a framework
Watch out for embedded variables in S2Dao
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
What is object-oriented after all or just one thing to watch out for in programming
Rock-paper-scissors game for beginners in Java
Multithreaded to fit in [Java] template
[For beginners] Run Selenium in Java
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
How to do base conversion in Java
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 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
Java to C and C to Java in Android Studio
[For beginners] How to debug in Eclipse
Add SameSite attribute to cookie in Java
[Java] [Microsoft] Things to be aware of when including the JDBC driver for SQL Server in one jar
For my son who started studying Java with "Introduction to Java" in one hand
[Java] Is it unnecessary to check "identity" in the implementation of the equals () method?
[Java] How to test for null with JUnit
Two ways to start a thread in Java + @
Things to be aware of when writing Java
ChatWork4j for using the ChatWork API in Java
I want to send an email in Java.
How to display a web page in Java
CORBA seems to be removed in Java SE 11. .. ..
Code to escape a JSON string in Java
Try to create a bulletin board in Java
Solution for NetBeans 8.2 not working in Java 9 environment
How to get Class from Element in Java