when comparing strings I prefer not to rely on instance methods lest the string on which the method is called happens to be null. In .NET I just use the static String.Compare(string, string, bool) method. does java provide a similar built-in "null-safe" string compare utility or do I have to implement my own?
We can compare String in Java on the basis of content and reference. It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc. There are three ways to compare String in Java: By Using equals() Method.
Using String.equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true.
The compare() method in Java compares two class specific objects (x, y) given as parameters. It returns the value: 0: if (x==y) -1: if (x < y)
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
No, JDK does not contain such utility. However there are several external libraries that do that. For example org.apache.commons.lang.StringUtils
provides null-safe equals(String, String)
and equalsIgnoreCase(String, String)
. Guava has similar utilities too.
There isn't. Apache Commons' StringUtils.equals()
does it this way:
public static boolean equals(String str1, String str2) {
return str1 == null ? str2 == null : str1.equals(str2);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With