![]() In the above examples, the first two comparisons are true because str1, str2, and str3 all have the same contents irrespective of 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. This method compares two strings based on their contents - character by characters, ignoring their references. The equals() method is part of String class inherited from Object class. It can potentially lead to unexpected results if you are not sure about the string types. ![]() This is because both these strings are pointing to different objects (literal vs object).īe careful while using comparison ( =) operator for matching strings. On the other hand, when we compare the 2nd string with 3rd string, it returns false. The comparison between 1st and 2nd string returns true because both these variables refer to the same string literal. String str1 = "Spring Boot" String str2 = "Spring Boot" String str3 = new String ( "Spring Boot" ) System. It returns true if both strings refer to the same object, otherwise false. It does not take into account strings' values and the only checks the referential equality of two strings. The comparison operator compares two strings by their reference. In this tutorial, we will learn about the following ways to compare two strings with each other: Strings can be compared based on their content as well as their reference. Since String is a popular data type in Java, the string comparison is probably one of the most commonly used operations.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |