How to compare strings in Java?
In my program, I used the ==
operator to compare strings. But I came across a bug, and when replacing ==
with equals
, it disappeared.
Should the ==
operator be avoided? When can it be used and when not? What's the difference?
2 answers
The ==
operator compares links.
The equals
method compares the 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 thanks to the string pool (string interning). These cases are explicitly described in the Java language specification.
The ==
operator is used to check that two strings 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 ==
is noticeably faster than equals
(comparing a reference instead of calling a method and a character-by-character comparison if the strings are of different lengths), so if you are working with strings from a pool (either the system or your own), replacing equals
with ==
can lead to a noticeable acceleration. But this happens very rarely.
Beware of calling equals
on null
! The ==
operator perfectly compares strings if one or more of them is equal to null
, but calling the equals
method on a string equal to null
will result in an exception.
To compare strings that can be equal to 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, such as Apache Commons.
If you use modern development environments, they will warn you if you try to compare strings using the ==
operator. Always pay attention to such things warnings.
In short, ==
compares references to an object, if the references point to the same object, then it is true, otherwise false, in the case of primitive types ==
compares values.
equals ()
it is used in String
so, it takes and compares each String
character by character, but this is only with String
, if you take the other objects (you created objects Яблоко
and Груша
), while these classes do not have the equals
method, then it is like ==
compares references to an object, if it is the same object, then tru otherwise false.
In String
, the equals ()
method is written, which compares character-by-character, so you need to use equals ()
{[15 withString
]}