What use does the == operator have for String?

In Java, if you need to check if two strings are equal, in the sense that their values ​​are the same, he / she should use the equals method. For instance.

 String foo = "foo"; String bar = "bar"; if(foo.equals(bar)) { /* do stuff */ } 

And if someone wants to check referential equality, he needs to use the == operator on two lines.

 if( foo == bar ) { /* do stuff */ } 

So my question is, does the == operator use the String class? Why do you need to compare references to String?

Edit: What I'm not asking: how to compare strings? How does == work? How does the equals method work?

What I'm asking is what the == operator uses for the String class in Java? What is the excuse for not overloading him so that he makes a deep comparison?

+6
source share
11 answers

Imagine a thread-safe Queue<String> acts as a communication channel between a producer stream and a consumer stream. It seems quite reasonable to use a special String to indicate completion.

 // Deliberate use of `new` to make sure JVM does not re-use a cached "EOT". private static final String EOT = new String("EOT"); ... // Signal we're done. queue.put(EOT); // Meanwhile at the consumer end of the queue. String got = queue.get(); if ( got == EOT ) { // Tidy shutdown } 

Please note that this will be resistant to:

 queue.put("EOT"); 

because "EOT" != EOT , although "EOT".equals(EOT) will be true .

+15
source

What is the use of this? Not much in normal practice, but you can always write a class that works with intern() -ed strings, which can then use == to compare them.

Why is it not overloaded, this is a simpler question: because in Java there is no operator overload. (To damage it a bit, the + operator was overloaded for strings, which was done in order to make string operations a little less cumbersome. But you can say that it is just syntactic sugar and, of course, overloading operators in Java bytecode. )

The absence of an overloaded operator == made using the operator much less ambiguous, at least for reference types. (That is, until the autoboxing / unboxing point was introduced, which again pollutes the water, but this is another story.) It also allows you to have classes like IdentityHashMap that will behave the same for every object that you put into it .

Having said all this, the decision to avoid operator overload (if possible) was a rather arbitrary design choice .

+10
source

The == operator compares a link between two objects. For example, if String x and String y refer to two different things, then the == operator will show false. However, the String.equals() method is not compared if they refer to each other, but if the values ​​(for example, "Hello", "World", etc.) match.

0
source
 // A.java String foo1 = "foo"; // B.java String bar1 = "foo"; 

All string literals implemented at compile time are added to the String Constant Pool. Therefore, when you have two different String declarations in two different classes, two String objects will not be created, and both foo1 and bar1 refer to the same String instance of the value foo . Now that you have a reference to String in two different variables, you can simply check if the two strings are equal by simply using == , which is fast because everything it does compares the bit pattern, where, like in the equals() method, each character is compared and is usually used for two different String instances, but the same content.

In fact, if you look at the implementation of equals() in the String class, the first check they perform is to compare references using == , because they may seem like different instances to you, but if they are string literals or if they're interned by someone else already, then all you have is a single link in two variables.

  public boolean equals(Object anObject) { if (this == anObject) { return true; } // remaining code } 

In addition, == is not only intended for strings, it is used to compare any two bit patterns, be it primitives or links

0
source

1. "==" comparison operation - the values ​​of two variables are equal, since variables of a reference type are expressed by two variables in the heap memory address, the same thing, namely the stack has the same content.

2. "equals" Regardless of whether two working variable references to the same object on the heap, that is, the contents of the same.

0
source

String s = "string1"; creates 1 link and 1 object in the pool String s1 = "string1"; creates only 1 link and indicates that s is pointing to.

 s == s1 // true 

String s2 = new String ("string1"); creates 1 object on the heap, one in the pool and one link.

 //Since, s2 is pointing to different object so, s2 == s // false s1 == s // false 

Problem: So, suppose we want to check how many unique String objects are created and stored in the pool by the application during its launch,

We can have a singleton object that can have all String references stored in an array.

From the previous examples s, s1 and s2, finally, 1 object is created for s and s1 and for s2, 1 object (2 in total).

 //If we use equals method, all s.equals(s1) // gives true s1.equals(s2) // gives true //So, number of references present in the array of singleton object will be our //total number of objects created which equals to 3 // doesn't match actual //count which is 2 

we can use == to check if the link is equal, so if the link is equal, we will not increase the counter of the unique String object in the pool, and for each unequal result, we will increase the count.

here,

for

 s // count = 1 s1 == s // count remains same s2 == s // false, so count = 1 + 1 = 2 //We get total number of unique String objects created and got stored in pool using == 
0
source

Simple answer...

Why do I need to compare String references?

Because they want to compare String values ​​very quickly.

Strings are not always interned () . There are string constants, but it is possible that the string was manually created on the heap. Using intern () in a hand-crafted string, we can continue to use the reference comparison in our strings for value .

What is the excuse not to overload him so that he makes a deep comparison?

  • Since Java does not have operator overloading as a design solution
  • The operator '==' is always a reference operator, and equals () is always a value method. In C ++ you can change this, but many find it just messing up the code.
0
source
  • Checking links Faster than checking if all rows are equal.

    • Suppose you have large strings (URLs or DBMS requests), they have several links to them. To check if they are equal, you can check the character by character, or you can check if they refer to the same object.
    • In fact, the equals method in java first checks to see if the links are the same and only if it does not go forward and checks the character by character.

  • Java is full of references, and therefore, you may need a case where you need to check whether two variables refer to the same String / Object, and not to both copies of the same string so that the string can be updated in one place and is reflected in all variables.
    • The equals method does not help for this, since it also checks for copies. you need to check whether they refer to the same object on the same object, and therefore in the picture.
0
source

It seems like this was asked earlier and got a pretty popular answer here:

Why comparison of operator line == == values ​​did not get into Java?

The simple answer: consistency

I guess this is just a sequence, or the "principle of least surprise." A string is an object, so it would be surprising if it was treated differently than other objects.

0
source

Although this is not a fundamental reason, use could improve performance: before performing heavy calculations, β€œinternalize” your lines ( intern() ) and use only == for comparison.

0
source

What I'm asking is what the == operator uses for the String class in Java? What is the excuse that he does not overload him, so that he makes a deep comparison?

== and equals have a completely different application. == confirms whether reference equality exists Equals confirms whether objects are the same.

An example of reference equality is IdentityHashMap. There may be a case when only an object inserting something into the IdentityHashMap has the right to receive / delete the object.

overloading reference equality can lead to undesirable complexity for java. for example if (string) {do deep equality} else {make referential equality}

/ ***************************************.... **************** /

Public class IdentityHashMap extends AbstractMap implements Map, Serializable, Cloneable

This class implements a Map interface with a hash table, using referential equality instead of equality of objects when comparing keys (and values). In other words, in IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1 == k2). (In normal map implementations (for example, HashMap), two keys k1 and k2 are considered equal if and only if (k1 == null? K2 == null: k1.equals (k2)).)

This class is not a general purpose map implementation! Although this class implements the Map interface, it intentionally violates the general Map contract, which provides for the use of the equals method when comparing objects. This class is intended for use only in rare cases when the semantics of referential equality is required.

0
source

Source: https://habr.com/ru/post/983136/


All Articles