Как сравнить строки в Java? Сравниваем строки в Java
В этой статье мы рассмотрим операторы и методы сравнения строк в Java. Поговорим про особенности использования оператора == , а также про методы equals(), equalsIgnoreCase и compareTo(), т. к. они используются чаще всего.
Оператор для сравнения строк «==»
В первую очередь, надо сказать, что этот оператор проверяет и сравнивает не значения, а ссылки. С его помощью вы сможете проверить, являются ли сравниваемые вами элементы одним и тем же объектом. Когда 2 переменные String указывают на тот же самый объект в памяти, сравнение вернёт true, в обратном случае — false.
В примере выше литералы интернируются компилятором, в результате чего ссылаются на один и тот же объект.
new String("Java") == "Java" // falseВышеприведённые переменные String указывают уже на различные объекты.
new String("Java") == new String("Java") // falseЗдесь тоже вышеприведенные переменные String указывают на различные объекты.
Итак, мы видим, что оператор == по сути, сравнивает не две строки, а лишь ссылки, на которые указывают строки.
class TestClass< public static void main (String[] args)< // ссылается на тот же объект, возвращая true if( "Java" == "Java" )< System.out.println("Statement is true"); >else < System.out.println("Statement is false"); >// указывает уже на другой объект, возвращая false if(new String("Java") == "Java")< System.out.println("Statement is true"); >else < System.out.println("Statement is false"); >// указывает тоже на другой объект, возвращая false if(new String("Java") == new String("Java") )< System.out.println("Statement is true"); >else < System.out.println("Statement is false"); >> >Statement is true Statement is false Statement is falseМетод сравнения String equals()
Сравнение строк с помощью equals позволяет проверять исходное содержимое строки. Метод возвращает true, когда параметр — объект String, представляющий собой ту же строку символов, что и объект:
Objects.equals("Java", new String("Java")) //trueКогда надо выполнить проверку, имеют ли 2 строки одинаковое значение, мы можем задействовать Objects.equals() .
class TestClass< public static void main (String[] args) < String str1 = "Java"; String str2 = "Java"; String str3 = "ASP"; String str4 = "JAVA"; String str5 = new String("Java"); // оба равны и возвращают true if(str1.equals(str2))< System.out.println("Statement is true"); >else < System.out.println("Statement is false"); >// оба не равны и возвращают false if(str1.equals(str3))< System.out.println("Statement is true"); >else < System.out.println("Statement is false"); >// оба не равны и возвращают false if(str1.equals(str4))< System.out.println("Statement is true"); >else < System.out.println("Statement is false"); >// оба равны и возвращают true if(str1.equals(str5))< System.out.println("Statement is true"); >else < System.out.println("Statement is false"); >> >Statement is true Statement is false Statement is false Statement is trueМетод сравнения String equalsIgnoreCase()
С помощью метода equalsIgnoreCase() вы выполните сравнение строк, что называется, лексикографически, причём различия регистра будут игнорированы. Здесь значение true возвращается в том случае, если аргумент является объектом String и представляет такую же последовательность символов, что и у объекта. Прекрасное решение, если надо осуществить проверку строки на равенство, не учитывая при этом регистр.
class TestClass< public static void main (String[] args)< String str1 = "Java"; String str2 = "JAVA"; // возвращается true, ведь обе строки равны без учёта регистра if(str1.equalsIgnoreCase(str2))< System.out.println("Statement is true"); >else < System.out.println("Statement is false"); >// возвращается false, т. к. учитывается регистр символов if(str1.equals(str2))< System.out.println("Statement is true"); >else < System.out.println("Statement is false"); >> >Statement is true Statement is falseМетод сравнения String compareTo()
Метод сравнения compareTo() применяется, если надо определить лексикографический порядок строк. Он выполняет сравнение значения char, действуя аналогично equals(). Когда 2 строки совпадают, compareTo() вернёт значение «ноль» (результат = 0). Сравнивая 2 строки, он вернёт положительное целое число (результат > 0), если 1-й объект String следует за 2-й строкой. Соответственно, метод вернёт отрицательный результат (результат < 0), когда 1-й объект String будет предшествовать 2-й строке:
result1 == result2 :возвращается 0; result1 > result2 :возвращается положительное значение; result1 < result2 : возвращается отрицательное значение.Приведём пример:
На этом всё, очень надеемся, что этот материал будет вам полезен при сравнении строк в "Джава".
При подготовке статьи использовалась публикация «String Comparison in Java».
Хотите знать больше? Приходите на курс!
4 ways to compare strings in Java
Since String is a popular data type in Java, the string comparison is probably one of the most commonly used operations. Strings can be compared based on their content as well as their reference.
In this tutorial, we will learn about the following ways to compare two strings with each other:
- By comparison ( == ) operator
- By equals() method
- By Objects.equals() method
- By compareTo() method
The comparison operator compares two strings by their reference. It does not take into account strings' values and the only checks the referential equality of two strings. It returns true if both strings refer to the same object, otherwise false.
String str1 = "Spring Boot"; String str2 = "Spring Boot"; String str3 = new String("Spring Boot"); System.out.println(str1 == str2); // true System.out.println(str2 == str3); // false
Look at the above examples. The comparison between 1st and 2nd string returns true because both these variables refer to the same string literal. On the other hand, when we compare the 2nd string with 3rd string, it returns false. This is because both these strings are pointing to different objects (literal vs object). Be careful while using comparison ( == ) operator for matching strings. It can potentially lead to unexpected results if you are not sure about the string types.
The equals() method is part of String class inherited from Object class. This method compares two strings based on their contents — character by characters, ignoring their references. It returns true if both strings have equal length and all characters are in the same order:
String str1 = "Spring Boot"; String str2 = "Spring Boot"; String str3 = new String("Spring Boot"); String str4 = new String("SPRING BOOT"); System.out.println(str1.equals(str2)); // true System.out.println(str2.equals(str3)); // true System.out.println(str2.equals(str4)); // false
In the above examples, the first two comparisons are true because str1 , str2 , and str3 all have the same contents irrespective of their references. Although str4 has the same content in uppercase equals() returns false as it is case-sensitive.
Unlike == operator which handles null strings well, calling equals() method from a null string will cause a NullPointerException exception. However, if the string passed to equals() method is null, it returns false.
If you want to ignore the content case, use equalsIgnoreCase() method instead. This method is similar to equals() but does not consider the casing in characters while comparing strings:
System.out.println(str2.equalsIgnoreCase(str4)); // true
The compareTo() method is a part of String class and compares the strings character by character lexicographically and returns an integer value that indicates whether the first string is less than ( < 0 value), equal to (0 value), or greater than (>0 value) the second string:
String str1 = "Spring Boot"; String str2 = "Spring Boot"; String str3 = new String("Spring Boot"); String str4 = new String("SPRING BOOT"); System.out.println(str1.compareTo(str2)); // 0 (true) System.out.println(str2.compareTo(str3)); // 0 (true) System.out.println(str1.compareTo(str4)); // 32 (false)
The compareToIgnoreCase() method is similar to compareTo() method except that it ignores characters case:
System.out.println(str1.compareToIgnoreCase(str4)); // 0 (true)
The Objects class is a part of the Java utility package which contains a static equals() method that can be used to compare two strings. This method returns true if both strings are equal to each other and false otherwise. Consequently, if both strings are null, true is returned and if exactly one string is null, false is returned. Otherwise, equality is determined by using the equals() method of the first string.
String str1 = "Spring Boot"; String str2 = "Spring Boot"; String str3 = new String("Spring Boot"); System.out.println(Objects.equals(str1, str2)); // true System.out.println(Objects.equals(str1, str3)); // true System.out.println(Objects.equals(null, str3)); // false System.out.println(Objects.equals(null, null)); // true
The StringUtils class from Apache Commons Lang library has some very good methods for performing string-related operations. The equals() method of StringUtils class is a null-safe version of the equals() method of String class, which also handles null values. The StringUtils class also includes equalsIgnoreCase() , compare() , and compareIgnoreCase() methods:
// use `equals()` and `equalsIgnoreCase()` methods System.out.println(StringUtils.equals("Spring Boot", "Spring Boot")); // true System.out.println(StringUtils.equalsIgnoreCase("Spring Boot", "SPRING BOOT")); // true // use `compare()` and `compareIgnoreCase()` methods System.out.println(StringUtils.compare("Spring Boot", "Spring Boot")); // true System.out.println(StringUtils.compareIgnoreCase("Spring Boot", "SPRING BOOT")); // true // `null` values System.out.println(StringUtils.equals(null, "SPRING BOOT")); // false System.out.println(StringUtils.equals(null, null)); // true
Before you start using StringUtils utility class methods, make sure that you have added Apache Commons Lang dependency to your project's pom.xml file:
dependency> groupId>org.apache.commonsgroupId> artifactId>commons-lang3artifactId> version>3.9version> dependency>
implementation 'org.apache.commons:commons-lang3:3.9'
That's folks for comparing strings in Java. We discussed 4 different ways to compare two strings with each other. You should always use Objects.equals() as it is null-safe and performs better. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.