[Java] [Java] Difference between equals and == in reference type character strings

2 minute read

Reference location comparison and value comparison

| Comparison method | Contents | |:–|:–| |equals| Comparing memory areas | |==| Compare values |

Program example

public class MyApp {
It's a sequel.
public static void main (String [] args) {

String s1 = "ab"; // Store memory area
String s2 = "ab"; // Store memory area (same area as above)

if (s1.equals (s2)) {// Compare if the contents are the same
System.out.println("same1 equals");

if(s1 == s2) {/ / comparison of basic data types
System.out.println("same2 ==");
// Create a string object (has an equals method)
String ss1 = new String ("ab"); // Storage of memory area
String ss2 = new String("ab"); // Storing memory area (create another area than above)

// Comparison of basic data types
if (ss1 == ss2) {// Since the memory area is being compared, it will be false, so it will not be executed.
System.out.println("same3 == object");
// Comparison of data contents
if(ss1.equals(ss2)) {
System.out.println ("same4 equals object"); // Executed because the memory area is different but the value is the same

Execution example

same1 equals
same2 ==
same4 equals object

The character string has a habit

In the character string that is originally a reference type, the location of the memory area of the reference destination is stored in the variable.

And in the example, the same character string ab is assigned to s1 and s2, but the location of the memory area is stored in s1 and the same character string is assigned to s2. It seems that the location of the area will be included. That is

String s1 = "ab";
String s2 = s1;

Same meaning as? become.

When I execute it for a trial

same1 equals
same2 ==
same4 equals object

Since the reference location is the same, what happens when the value of the reference destination is returned in either case? Does changing only the value of s1 change both?

String s1 = "ab";
String s2 = s1;
s2 = "cd";

What happens when…

System.out.println("s1: "+ s1);
System.out.println("s2: "+ s2);

Add and run.

Execution result

s1: ab
s2: cd
same4 equals object

Only s2 has been changed and is not reflected in s1.

Speaking of which, character strings behave in the same way as basic data types, and they behave in the same way as int types. .. ..

It means that while the value is the same, it is the same reference destination, and when the value is updated, a new memory area is created?

It’s confusing, but I tried it and understood again.

If it is an array, both values will be updated. Review Review!