In my program, I used the == operator to compare strings. But I came across a bug, and when replacing == with equals it disappeared.

Should operator avoid == ? When can it be used and when not? What is the difference?

  • four
    Added another "canonical" answer. In English, SO is the most popular question as a target for closing duplicates. Mostly translate and compile How do I compare strings in Java? plus more on the little things. - Athari
  • one
    School at Hashcode :) - VladD
  • Sorry, but you asked yourself, and answered yourself? - Andrew Bystrov
  • 2
    @AndrewBystrov Yes. See en.stackoverflow.com/help/self-answer - Athari
  • 2
    @Discord xs. Maybe I'm wrong, but it is better to make one "reference" answer and a question and close all the others with exactly the same questions. If there is a desire to add on the topic, then improve the "reference" answer. - ReinRaus

2 answers 2

Operator == compares links.

The equals method compares values.

Therefore, if you want to compare strings for equality, you should use equals .

However, in some cases, strings are guaranteed to be represented by the same object due to string interning . These cases are explicitly described in the Java language specification .

The == operator is used to verify that two lines point to the same object.

 // Эти строки имеют одно и тоже же значение new String("test").equals("test") // --> true // ...но это разные объекты new String("test") == "test" // --> false // ...эти строки тоже разные объекты new String("test") == new String("test") // --> false // ...но эти строки указывают на один и тот же объект, // потому что компилятор добавляет все литералы в пул. "test" == "test" // --> true // Конкатенация литералов тоже происходит на стадии компиляции, // поэтому они указывают на один объект "test" == "te" + "st" // --> true // но вызов substring() происходит во время выполнения, // в результате получаются разные объекты. "test" == "!test".substring(1) // --> false // Строки из пула могут быть получены с помощью вызова intern(). "test" == "!test".substring(1).intern() // --> true 

It should be noted that == noticeably faster than equals (comparing a link instead of calling a method and character-by-character comparison if the strings are of different lengths), so if you work with strings from the pool (or system, or your own), replacing equals with == can lead to a noticeable acceleration. But this happens very rarely .

Beware of calling equals to null ! The == operator perfectly compares strings if one or more of them is null , but a call to the equals method on a string equal to null will result in an exception.

To compare strings that can be null , you can use the following method:

 public static boolean equals(String str1, String str2) { return str1 == null ? str2 == null : str1.equals(str2); } 

It is present in some third-party libraries, for example, in Apache Commons.

If you are using modern development environments, they will warn you if you try to compare strings using the == operator. Always pay attention to such warnings.

  • 2
    If this is a canonical answer, maybe write about interning? - VladD
  • @VladD In my opinion, this is a separate question. For those who are interested in how to compare strings, the details of working with interning are a bit early to tell. :) - Athari
  • Maybe then instead of "However, in some cases, the lines are guaranteed to be represented by the same object" for example. In some cases, a comparison through == can give the correct result (see interning for details), but you can’t hope so, unless you clearly understand what you are doing."? - VladD
  • @VladD "Hope" is an unfortunate word when there is a formal specification. Important cases are described in the example, and it would be superfluous to drag all the details from the specs to this answer. If you want to write about interning, you can create a separate QA, paint the criteria in detail, paint the use cases, advantages, disadvantages, pitfalls, etc. Then from this question one could refer. In my opinion, this would be optimal. - Athari
  • Well, we are writing an informal explanation? "Count"? - VladD

In short, == compares object references, if links point to the same object, then this is true, otherwise false, in the case of primitive types == compares values.

equals () used in String so it takes and compares each String character by character, but this is only with String , if you take the remaining objects (you created the Яблоко and Груша objects), and the equals method is not registered in these classes, then it is == compares links to an object, if it is the same object, then I rub false otherwise.

In the String the equals () method is registered, which compares character-by-character, so you should use equals () with String