Unlike Java, C# strings override the == operator:
if (str1 == str2)
If you want a case-insensitive comparison:
if (string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase))
Answer from SLaks on Stack OverflowVideos
Unlike Java, C# strings override the == operator:
if (str1 == str2)
If you want a case-insensitive comparison:
if (string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase))
If you do not want to treat two null strings as equal to each other, your code is optimal.
If, on the other hand, you want to treat null values as equal to each other, you can use
object.Equals(str1, str2)
for a more "symmetric" approach that also handles null values.
This is not the only approach to a symmetric check of string equality that treats null strings as equal: you could also use string.Equals(str1, str2) or even str1 == str2, which redirects to string.Equals.
I need to simply check if an object in a string vector is null or not:
std::vector<string> vliwSlots;
//Some inserts...
string vliwSlot = vliwSlots.at(i); //in a for loop
if(vliwSlot != NULL){ //error on this line
//Do stuff
}When I compile this I get the following error at :
no match for ‘operator!=’ (operand types are ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ and ‘long int’)
It seems it thinks NULL is a long int. How the heck do I check if a string is null?
Using "abc".equals(...) is a reasonable precaution against a condition you didn't anticipate, but doesn't really solve any problems. Maybe this particular method doesn't care that myString is null (the string comparison returns false, but that's it), but what about elsewhere? Now there's this null value working its way through your logic that's not supposed to be there.
In this particular case, it might not matter, but in another, letting this invalid value pass through part of the logic could lead to an incorrect state later on (e.g. an address with the city missing). Fail early!
If myString should not be null, then write the code so that it can't be. Add contracts to your methods, or at least some in-method argument validation to ensure invalid values are dealt with before the method's logic ever executes. Then be sure your tests cover these cases.
One goal of programming is robust code, ie. code that doesn't die horribly whenever something unexpected crops up.
in case of if ("abc".equals(myString)), the if clause doesn't get executed if the string is null, so throwing an exception isn't necessary. Of course it could be caused by bugs in code, but those should be found during developing/testing, not in production, by the customer!
Actually, i would take "abc".equals(myString) as an indication that the programmer explicitly didn't care whether the string was null or not. In critical code, i'd expect a lot more explicit checking.
You cannot use the dereference (dot, '.') operator to access instance variables or call methods on an instance if that instance is null. Doing so will yield a NullPointerException.
It is common practice to use something you know to be non-null for string comparison. For example, "something".equals(stringThatMayBeNull).
Use Objects.equals() to compare strings, or any other objects if you're using JDK 7 or later. It will handle nulls without throwing exceptions. See more here: how-do-i-compare-strings-in-java
And if you're not running JDK 7 or later you can copy the equals method from Objects like this:
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
You may also understand the difference between null and an empty string this way:

Original image by R. Sato (@raysato)
"" is an actual string, albeit an empty one.
null, however, means that the String variable points to nothing.
a==b returns false because "" and null do not occupy the same space in memory--in other words, their variables don't point to the same objects.
a.equals(b) returns false because "" does not equal null, obviously.
The difference is though that since "" is an actual string, you can still invoke methods or functions on it like
a.length()
a.substring(0, 1)
and so on.
If the String equals null, like b, Java would throw a NullPointerException if you tried invoking, say:
b.length()
If the difference you are wondering about is == versus equals, it's this:
== compares references, like if I went
String a = new String("");
String b = new String("");
System.out.println(a==b);
That would output false because I allocated two different objects, and a and b point to different objects.
However, a.equals(b) in this case would return true, because equals for Strings will return true if and only if the argument String is not null and represents the same sequence of characters.
Be warned, though, that Java does have a special case for Strings.
String a = "abc";
String b = "abc";
System.out.println(a==b);
You would think that the output would be false, since it should allocate two different Strings. Actually, Java will intern literal Strings (ones that are initialized like a and b in our example). So be careful, because that can give some false positives on how == works.
I prefer the explicit style (first version). It makes it obvious that there is a pointer involved and not an integer or something else but it's just a matter of style.
From a performance point of view, it should make no difference.
Equivalent. It says so in the language standard. And people have the damndest religious preferences!
string == null compares if the object is null. string.equals("foo") compares the value inside of that object. string == "foo" doesn't always work, because you're trying to see if the objects are the same, not the values they represent.
Longer answer:
If you try this, it won't work, as you've found:
CopyString foo = null;
if (foo.equals(null)) {
// That fails every time.
}
The reason is that foo is null, so it doesn't know what .equals is; there's no object there for .equals to be called from.
What you probably wanted was:
CopyString foo = null;
if (foo == null) {
// That will work.
}
The typical way to guard yourself against a null when dealing with Strings is:
CopyString foo = null;
String bar = "Some string";
...
if (foo != null && foo.equals(bar)) {
// Do something here.
}
That way, if foo was null, it doesn't evaluate the second half of the conditional, and things are all right.
The easy way, if you're using a String literal (instead of a variable), is:
CopyString foo = null;
...
if ("some String".equals(foo)) {
// Do something here.
}
If you want to work around that, Apache Commons has a class - StringUtils - that provides null-safe String operations.
Copyif (StringUtils.equals(foo, bar)) {
// Do something here.
}
Another response was joking, and said you should do this:
Copyboolean isNull = false;
try {
stringname.equalsIgnoreCase(null);
} catch (NullPointerException npe) {
isNull = true;
}
Please don't do that. You should only throw exceptions for errors that are exceptional; if you're expecting a null, you should check for it ahead of time, and not let it throw the exception.
In my head, there are two reasons for this. First, exceptions are slow; checking against null is fast, but when the JVM throws an exception, it takes a lot of time. Second, the code is much easier to read and maintain if you just check for the null pointer ahead of time.
Copys == null
won't work?
When I type
string1 == string2
IntelliJ tells me to switch to equals(), which it says is null-safe.
But is == operator not null-safe?
I tried null == "abc", "abc" == null, null == null, but they consistently gave me right false false true.
What am I missing here?