Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does java provide a built-in static String.Compare method?

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?

like image 367
John Smith Avatar asked Feb 07 '13 15:02

John Smith


People also ask

Can you compare strings in Java?

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.

Which method is used to compare two strings Java?

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.

What is compare () in Java?

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)

Can we use == to compare strings in Java?

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.


2 Answers

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.

like image 107
AlexR Avatar answered Oct 16 '22 01:10

AlexR


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);
}
like image 31
Xavi López Avatar answered Oct 15 '22 23:10

Xavi López