7/30/2023 0 Comments Java string equalityLet's create an object and get the String representation of it so we can see how the operator behaves. When the operands are objects, the = operator compares their references, or where they are stored in memory. It does not check the value stored in those objects. While the = operator can be used safely to compare primitive integers, it is a mistake to use it on strings. out.println(name.equals( "Amir")) // NullPointerException Why not use the = operator? out.println( "Amir".equals(name)) // false Let's take a look at some code that demonstrates this fact: String name = null It will simply return false which is usually what we want. This is legal and actually the preferred approach over line 2.īecause it will not throw a NullPointerException if our name variable happens to be null. Notice on line 3 how we swapped the order of the string literal and variable. out.println( "Amir".equals(name)) // true out.println(name.equals( "Amir")) // true When comparing a string variable to a literal, we can write it a couple different ways: String name = "Amir" (name1.equalsIgnoreCase(name2)) // true Avoiding Exceptions with equals() Sometimes, we may not care about case sensitivity. We can use the equalsIgnoreCase()method in this situation: String name1 = "Amir" Let's check out some code that uses the method: Object obj = new Object() The String class contains an equals() method that's used to determine whether two strings are the same. It returns a boolean. In this article, we'll demonstrate how to compare strings in Java for equality and discuss some of the common pitfalls developers encounter along the way.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |