[Java] About Objects.equals () and Review of String comparisons (== and equals)

Java engineer Akuma-chan @akumachanit demo! Today is a demo that talks about string comparison!

Java 1.7 is here

** When are you talking ** demo? Akuma-chan was ** developing an application with JDK 1.6 at work ** (a demo that can be believed in the Reiwa era? But it's quite a demo to upgrade!), But recently it has been upgraded. A demo that allows you to use the features of 1.7!

Objects Demo with Objects in the class added from 1.7. It seems that 1.7 was released in 2011, so I think there are many people who are reading this demo who haven't become engineers yet. I'm sorry to talk about this now. (Demonstration that Wagamama was not an engineer at that time).

So, when using the method ʻObjects.equals () of that ʻObjects, I checked the specifications for the time being, so here is a demo.

A demo written in the ʻObjects` specification as follows.

This class (...) contains null-safe or null-tolerant methods for comparing two objects.

In other words, what does that mean?

if(a.equals("test")) { //NullPointerException if a is null
}

If you write code like this, if ʻaisnull, NullPointerExceptioin will occur. There is no ʻequals method (or anything) in null, so it's a natural demo. In such a case, it was necessary to put the character string first and perform the null check first.

if("test".equals(a)) { //Absolutely no NullPointerException
}
if(a != null && a.equals("test")) { //If null, skip the judgment
}

The above example can't be used as variables where both can be null, and it's not super beautiful to write the same thing every time like the example below! Objects.equals() ʻObjects.equals () `!! that appeared dashingly there

Objects.equals(a, "test"); //Like this

public static boolean equals(Object a, Object b) Returns true if the arguments are equal to each other, false otherwise. Therefore, if both arguments are null, true is returned, and if only one argument is null, false is returned. Otherwise, the equals method of the first argument is used to determine if they are equal.

ʻObjects.equals ()is a demo that returnstrue even if both are null! This is a demo that cannot be done with the conventional method mentioned above! Well, such a convenient ʻObjects.equals (), but what happens when you try to compare strings?

Review about string comparison

Demo that everyone who is doing Java knows that ** Strings should not be used for comparison **! A demo that people who didn't know will definitely remember and return here. It's a demo that you'll have a hard time using without knowing it.

About the equality operator (==)

First of all, a demo that looks at the Java specification for equality operators.

15.21. Equality Operators The equality operators may be used to compare two operands that are convertible (§5.1.8) to numeric type, or two operands of type boolean or Boolean, or two operands that are each of either reference type or the null type. All other cases result in a compile-time error.

(Appropriate translation) Equivalence operators can be used between "two operands that can be converted to numeric type", "between two operands that are boolean or Boolean", and "between operands that are reference type or null type". Other patterns will result in a compile-time error.

Since String is a reference type, a demo to read about the comparison between a reference type and a null type.

15.21.3. Reference Equality Operators == and != At run time, the result of == is true if the operand values are both null or both refer to the same object or array; otherwise, the result is false.

(Appropriate translation) At runtime, the result of == is true if the values of the two operands are "both null" or "both refer to the same object or array", otherwise false. ..

In other words, == is a demo that verifies whether the referenced object is the same.

If you use == in String

Then, a demo to see the code that actually compares the == of String.

String a = "test";
String b = "test";

System.out.println(a == b);               // true

that? No problem demo, right? ?? ?? Then how about this demo?

String a = "test";
String b = new String("test");

System.out.println(a == b);               // false

that? A demo where the result is false after substituting new for String into b, right? Then how about this demo?

String a = "test";
String b = "te".concat("st");

System.out.println(a == b);               // false

This is also a demo that has become false!

The reason for this is that in Java ** string literals ** (strings enclosed in double quotes, like " test ") ** refer to the same String type instance. **demo. In other words, a demo that contains a reference to the same String type instance no matter how many times you assign"test".

So, the first example is a demo where something like this is happening internally.

String x = new String("test");
String a = x;
String b = x;

System.out.println(a == b);               // true

This is an easy-to-understand demo! Since both ʻa and brefer tox, it is a convincing demo that ʻa == b is true.

So why wasn't it equal in the second and third examples? If you use new String () to generate a string, it will create a new instance even if the values are the same ** Demo .. A demo of concat () also internally using new String () to return a new string. (However, note that concat () returns the original instance as it is if the length of the argument string is 0.)

Now, this is a demo where you can't use == to compare strings. The reason is that even if the values of ** String ** to be compared are the same, there is no guarantee that they refer to the same instance ** Demo. So how can you verify a string with different instances and the same value? !! That's where the String # equals () method demo comes in! !! !!

String#equals() The String # equals () method is a demo that validates the value of a String!

String a = "test";
String b = new String("test");

System.out.println(a.equals(b));          // true

Alright! This is the solution demo! It's a demo that doesn't require explanation at this point. For comparison of String ** String # equals ()! !! This is a perfect demo! !! ** ** ... the demo that seems to be ... finally reaches the problem at the beginning here.

// String#equals()Unsightly code demos that you have to write with
if("test".equals(a)) { //Absolutely no NullPointerException
}
if(a != null && a.equals("test")) { //If null, skip the judgment
}

Hmmmm! The demo that I finally arrived at! Here is the production demo!

Objects.equals () does a null check

The demo I mentioned at the beginning is that # Objects.equals () checks null, and when you compare nulls, it returns true!

String a = null;
String b = null;
Objects.equals(a, b); // true -Does not result in NullPointerException

String a = null;
String b = "test";
Objects.equals(a, b); // false -Does not result in NullPointerException

So, a demo that made me wonder. ** What happens to string comparisons? ** **

The reason why I thought about that is that String # equals () is actually a demo that compares values, but its parent class ʻObject has ʻObject # equals () is **. A demo comparing ** referenced instances rather than values. More specifically, a demo that uses == internally.

// Object#equals()
public boolean equals(Object obj) {
    return (this == obj);
}

String # equals () is a demo that ** overrides ʻObject # equals ()` and rewrites the process **.

So, when you know ʻObjects # equals (), it's named ʻObject, so it behaves the same as ʻObject # equals`? I thought it was a demo. The answer is the demo in the method specifications I wrote at the beginning.

~ (Omitted) Otherwise, the equals method of the first argument is used to determine if they are equal.

A demo in which the ** first argument ʻequals method ** is specified if both arguments are not null. In other words, if you pass a value of type Stringas the first argument, it will compare the values. If the first argument is other thanString and the second argument is String, it's false anyway, so the contents of the argument ʻequals method are irrelevant demo.

Summary

** Demo using Objects.equals ()! !! !! ** **

References

Official oracle stuff and demos.

Recommended Posts

[Java] About Objects.equals () and Review of String comparisons (== and equals)
[Java] About String and StringBuilder
[Java] The confusing part of String and StringBuilder
NIO.2 review of java
Review of java Shilber
[Java] String comparison and && and ||
About Java String class
NIO review of java
The comparison of enums is ==, and equals is good [Java]
[Java] Handling of character strings (String class and StringBuilder class)
About an instance of java
[Java] Difference between == and equals
[Java Silver] About equals method
[Java] HashCode and equals overrides
Advantages and disadvantages of Java
About Java Packages and imports
[Java] Set structure of collection class (about HashSet and TreeSet)
Recommendation of set operation by Java (and understanding of equals and hashCode)
[Java] I thought about the merits and uses of "interface"
[Java] Speed comparison of string concatenation
About Java static and non-static methods
About miscellaneous impressions of "Testing Java Microservices" and Consumer Driven Contract
Various methods of Java String class
About Lambda, Stream, LocalDate of Java8
About the equals () and hashcode () methods
[Java beginner] About abstraction and interface
[Java beginner] == operator and equals method
About the relationship between the Java String equality operator (==) and initialization. Beginners
[Java] Judgment of identity and equivalence
About removeAll and retainAll of ArrayList
Understanding equals and hashCode in Java
I tried to summarize the methods of Java String and StringBuilder
About Java primitive types and reference types
[Ruby] Review about nesting of each
Studying Java 8 (String Joiner and join)
[Java] Correct comparison of String type
This and that about Base64 (Java)
About the classification and concept of Immutable / Mutable / Const / Variable of Java and Kotlin.
Review of "strange Java" and Java knowledge that is often forgotten in Java Bronze
About the operation of next () and nextLine ()
[Java] Inheritance and structure of HttpServlet class
[About JDBC that connects Java and SQL]
[Java / Swift] Comparison of Java Interface and Swift Protocol
[Java beginner] About initialization of multidimensional array
[Basic knowledge of Java] About type conversion
[Java] Comparison of String type character strings
About the mechanism of the Web and HTTP
Summary of Java Math.random and import (Calendar)
[Java] Contents of Collection interface and List interface
Basics of java basics ② ~ if statement and switch statement ~
Discrimination of Enums in Java 7 and above
Java string
== and equals
Java review
The story of low-level string comparison in Java
Think about the combination of Servlet and Ajax
About the description order of Java system properties
Review notes for Java 1.7 and later file copies
[Java] Personal summary of classes and methods (basic)
About Java data types (especially primitive types) and literals
[Java] Get the length of the surrogate pair string