When you want to test your strings for equality in this case-insensitive manner, use the equalsIgnoreCase method of the String class, like this: In some string comparison tests you'll want to ignore whether the strings are uppercase or lowercase. Solution 2: String comparison with the 'equalsIgnoreCase' method test for equality with the java string equals method ("The two strings are the same.")īut, when the two strings contain the exact same string of characters, the equals method will return true, as in this example: ![]() java string equals method returns false: Taking a look at a quick String comparison example with the equals method, if the following test were run, the two strings would not be considered equal because the characters are not the exactly the same (the case of the characters is different): ![]() The String equals method looks at the two Java strings, and if they contain the exact same string of characters, they are considered equal. Most of the time - maybe 95% of the time - I compare Java strings with the equals method of the String class, like this: Solution 1: Java String comparison with the 'equals' method At the end of this tutorial I’ll also discuss why the = operator doesn’t work when comparing Java strings. ![]() In this tutorial I’ll demonstrate several different ways to correctly compare Java strings, starting with the approach I use most of the time. If you’re like me, when I first started using Java, I wanted to use the = operator to test whether two String instances were equal, but that's not the correct way to do it in Java. Java String comparison FAQ: Can you share some examples of how to compare strings in Java?
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |