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).
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));
}
Copyif (myString != null && !myString.isEmpty()) {
// doSomething
}
As further comment, you should be aware of this term in the equals contract:
From Object.equals(Object):
For any non-null reference value
x,x.equals(null)shouldreturn false.
The way to compare with null is to use x == null and x != null.
Moreover, x.field and x.method() throws NullPointerException if x == null.
If myString is null, then calling myString.equals(null) or myString.equals("") will fail with a NullPointerException. You cannot call any instance methods on a null variable.
Check for null first like this:
Copyif (myString != null && !myString.equals("")) {
//do something
}
This makes use of short-circuit evaluation to not attempt the .equals if myString fails the null check.
if(dates[i] != null);
^
the extra ; causes the following block to always execute (regardless of the evaluation of the if statement), since it ends the if statement. Remove it.
The problem is ';' after if(condition); that ends the statement and treats the remaining piece of code in normal manner irrespective of any condition.
Code
package bank;
public class HowCheckForNull {
static void showDates(String[] dates){
for(int i = 0; i < dates.length; i++){
System.out.println(dates[i]);
System.out.println(dates[i] == null);
System.out.println(dates[i] == (String) null);
System.out.println(dates[i] != null);
if(dates[i] != null){ //Now it will not execute.
System.out.print("A transaction of X$ was made on the " + dates[i] + "\n");
}
}
System.out.println("");
}
public static void main(String args[]){
String[] dates = new String[3];
showDates(dates);
}
}
Output
null
true
true
false
null
true
true
false
null
true
true
false
1st one is better (and the only option), because 2nd one will throw NPE, when your value is actually null. As simple as that.
Try this out:
String str = null;
str.equals(null); // will throw `NPE`.
So basically, the test which you wanted to perform itself triggers a NullPointerException in the 2nd case. So, it is no choice.
!str.equals(null) will
- always return false if it does not throw an exception, and
- throw an exception if str is null
The point of a null check is to make sure the reference, in this code str, actually refers to an object. If it is null, you can't call any methods on it, including equals, without throwing a NullPointerException... which the point of null checks is to avoid happening.
So !str.equals(null) causes the very problem null checks are meant to prevent and doesn't do what you think at all. Never do this.
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?
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?
If Java 7+, use Objects.equals(); its documentation explicitly specifies that:
[...] if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals method of the first argument.
which is what you want.
If you don't, your method can be rewritten to:
Copyreturn s1 == null ? s2 == null : s1.equals(s2);
This works because the .equals() contract guarantees that for any object o, o.equals(null) is always false.
From Objects.equals():
Copyreturn (a == b) || (a != null && a.equals(b));
Very simple, self-explaining and elegant.
There's a key difference between a null array and an empty array. This is a test for null.
int arr[] = null;
if (arr == null) {
System.out.println("array is null");
}
"Empty" here has no official meaning. I'm choosing to define empty as having 0 elements:
arr = new int[0];
if (arr.length == 0) {
System.out.println("array is empty");
}
An alternative definition of "empty" is if all the elements are null:
Object arr[] = new Object[10];
boolean empty = true;
for (int i=0; i<arr.length; i++) {
if (arr[i] != null) {
empty = false;
break;
}
}
or
Object arr[] = new Object[10];
boolean empty = true;
for (Object ob : arr) {
if (ob != null) {
empty = false;
break;
}
}
ArrayUtils.isNotEmpty(testArrayName) from the package org.apache.commons.lang3 ensures Array is not null or empty
Since Java 7 you can use the static method java.util.Objects.equals(Object, Object) to perform equals checks on two objects without caring about them being null.
If both objects are null, it will return true, if one is null and the other isn't, it will return false. Otherwise, it will return the result of calling equals on the first object with the second as argument.
This is what Java internal code uses (on other compare methods):
public static boolean compare(String str1, String str2) {
return (str1 == null ? str2 == null : str1.equals(str2));
}
You should use equals() rather than compareTo(). compareTo() raises NullPointerException if passed null.
Java doc of Comparable
Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.
if (stringArray[i] == null) {
continue;
} else if (stringArray[i].equals(stringArray[j]) && i != j) {
// duplicate
duplicates++;
}
So complete source code should look like. I have not changed any logic inside your for loop.
String line = "DO UNTO OTHERS AS YOU WOULD HAVE THEM DO UNTO YOU";
String[] stringArray = line.split("\\s");//Use split StringTokenizer use is discouraged in new code
int duplicates = 0;
int wordCount = stringArray.length;
for (int j = 0; j < stringArray.length; j++) {
for (int i = j + 1; i < stringArray.length; i++) {
if (stringArray[i] == null) {
stringArray[i] = "null";
} else if (stringArray[i].equals(stringArray[j]) && i != j) {
// duplicate
System.out.print("\n" + stringArray[j]);
duplicates++;
}
}
}
wordCount -= duplicates;
System.out.print("\nNumber of words, not including duplicates: "
+ wordCount);
Drop your if (stringArray[i] == null) null check. It's not necessary. Instead, try printing out the array right after you initialize it and see whether wordCount may be too big, or perhaps the tokenizer is not breaking the string where you think it should.
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.
If you add a string to null, the null is converted to the string "null". For instance, null + " hi there" gives "null hi there".
So if wordInd[length] is null, and you execute
wordInd[length] += " " + word + " ";
Then you are concatenating null to a string, giving you a string starting with "null ".
Try checking for null:
if (wordInd[length]==null) {
wordInd[length] = word;
} else {
wordInd[length] += " "+word;
}
When you initialize an array in Java, every empty space of the array is filled with the default value depending of the type.
Since you are creating Arrays of Strings, every slot of the array will contain a "null" value.
Your program is doing what you asked it to do: Add a space -> a new String -> another space for each new word it finds.
Edit: NVM, your question has already been answered :)
No, because they are not the same. "" is very different from null.
Now if you want this behavior write a custom method:
static boolean checkIfEmptyOrNull(String s1, String s2) {
//check for empty and null
return myBooleanValue;
}
Mark this as static because this should be a helper (and should probably go in a helper class as well)
As oracle stores all empty strings as null, we have been mapping the respective columns with a custom data-type that maps all null-values in the database to empty strings. So all Strings read from the database will be empty instead of null.
To create this type you implement a class extending org.hibernate.usertype.UserType;:
import org.hibernate.usertype.UserType;
public class OracleStringType implements UserType {...}
Most required method-implementations are quite straightforward, as you just return the parameter passed in. The most interesting are these:
@Override
public boolean equals(Object arg0, Object arg1) throws HibernateException {
if(arg0 == null) arg0 = "";
if(arg1 == null) arg1 = "";
return arg0.equals(arg1);
}
@Override
public int hashCode(Object arg0) throws HibernateException {
if(arg0==null) arg0="";
return arg0.hashCode();
}
@Override
public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner)
throws HibernateException, SQLException {
String result = resultSet.getString(names[0]);
if(resultSet.wasNull()) return "";
return result;
}
@Override
public void nullSafeSet(PreparedStatement statement, Object value, int index)
throws HibernateException, SQLException {
if(value == null) {
statement.setNull(index, Hibernate.STRING.sqlType());
} else {
String valueString = (String)value;
statement.setString(index, valueString);
}
}
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.