I'm checking whether a List object is null or not using java. But I'm not sure whether it is the optimized way or not.
Here is my code:
List<String> listSCBPLNewErrMsgs= new ArrayList<String>(Arrays.asList(SCBPL_NEW_ERRORMESSAGES.split("\\$\\#")));
The above line itself throws null pointer exception.
if(listSCBPLNewErrMsgs != null) <Right way?>
This will get all the values from the config.
Now, tomorrow if I change the config entry, this should not throw an null pointer exception
The new operator in Java can never return null. Neither can String#split.
What you may want to check, however, is that the list is not empty:
if (listSCBPLNewErrMsgs.isEmpty()) {
// do something
}
If SCBPL_NEW_ERRORMESSAGES is null that code will still fail.
Assuming that SCBPL_NEW_ERRORMESSAGES has some value or is empty, the split will return an array of size 0 or more. Changing it to a list from an array will yield either an array with 0 or more elements.
Lastly, the copy constructor will copy the content and assign it to a new list. In all scenarios, unless there is a null pointer on SCBPL_NEW_ERRORMESSAGES, the returned list (listSCBPLNewErrMsgs) will never be null, at most it will be empty, which can be checked with the isEmpty() method call.
As per your comment, if you are getting a null pointer on that line, it should be due to the fact that SCBPL_NEW_ERRORMESSAGES is null.
Try this:
List<String> listSCBPLNewErrMsgs = null;
if(SCBPL_NEW_ERRORMESSAGES != null) {
listSCBPLNewErrMsgs= new ArrayList<String>(Arrays.asList(SCBPL_NEW_ERRORMESSAGES.split("\\$\\#")));
}
else {
listSCBPLNewErrMsgs = new ArrayList<>();
}
If you want to check whether it is null it is right way (even though it will never be null), however if you simply want to check if list is empty then you should use isEmpty() method:
if(listSCBPLNewErrMsgs.isEmpty()) {/**/}
From the looks if your code your listSCBPLNewErrMsgs object won't be null. Test if it is empty using the listSCBPLNewErrMsgs.isEmpty();
If SCBPL_NEW_ERRORMESSAGES is nulll that will throw a NPE exception indeed since you will be using the split method on null.
You can first check if that's not null:
if (SCBPL_NEW_ERRORMESSAGES != null) {
//Instantiate list
//Optional isEmpty check
}
You will first check if SCBPL_NEW_ERRORMESSAGES is not null
Then you can instantiate your list and perform an optional isEmpty check on the new list.
if(SCBPL_NEW_ERRORMESSAGES != null)
List<String> listSCBPLNewErrMsgs= new ArrayList<String>Arrays.asList(SCBPL_NEW_ERRORMESSAGES.split("\\$\\#")));
No Need of listSCBPLNewErrMsgs != null as everyone said
First you have to check SCBPL_NEW_ERRORMESSAGES is null or empty
if(!TextUtils.isEmpty(SCBPL_NEW_ERRORMESSAGES))
You have to check both whether the list is null/empty or not. So I prefer
if(listSCBPLNewErrMsgs != null && !listSCBPLNewErrMsgs.isEmpty()) {
}
You need to add null check for SCBPL_NEW_ERRORMESSAGES.
if (SCBPL_NEW_ERRORMESSAGES != null && !SCBPL_NEW_ERRORMESSAGES.isEmpty()) {
In your declaration, list can not be null as your are doing new ArrayList<String>.
So no need to worry about null pointer exception.
If you wish to check for empty list.
Then you can try isEmpty() method.
if (SCBPL_NEW_ERRORMESSAGES != null && !SCBPL_NEW_ERRORMESSAGES.isEmpty()) {
List<String> listSCBPLNewErrMsgs = new ArrayList<String>(Arrays.asList(SCBPL_NEW_ERRORMESSAGES.split("\\$\\#")));
if (!listSCBPLNewErrMsgs.isEmpty()) {
// Do something.
}
}
Related
Assume I want to check if the first element from a list is equal to "YES" or "NO".
dummy_method(List<String> myList) {
if(myList.isEmpty()) {
return null;
}
String firstListValue = myList.get(0).getStringValue();
// Should I do this:
if ("YES".equalsIgnoreCase(firstListValue)) {
return firstListValue;
}
// OR this:
if (firstListValue.equalsIgnoreCase("YES")) {
return firstListValue;
}
// Do something else
}
In other words: Does the order of if A equals B versus if B equals A matter when I already have a null-check?
Yes. It matters.
You have only checked if the list is non-empty. If the first element in the list is null then you will get a NullPointerException at
firstListValue.equalsIgnoreCase("YES")
But, if you can ensure all the elements (or at least the first element) in the list are non-null, then both the statements are equivalent.
For null safety you can use your first if like this:
if ("YES".equalsIgnoreCase(firstListValue)) {
return firstListValue;
}
because "YES" is hardcoded string and won't be null. Where as in 2nd approach, whenever the list element is null, you will get NullPointerException.
This check will also throw NullPointerException if the list is null, so you can check both conditions
if(myList!=null && !myList.isEmpty())
And also need 'null' check for all values retrieved through 'get()' , because if list is empty or specified index is out of range 'get()' method will not throw 'NullpointerException', it will just return null
I was reviewing a Java project and saw the following code:
List<XYZ> xyzList = new ArrayList<>();
............................
do some things with the list
............................
if (xyzList != null && xyzList.size() > 0) doSomething();
Is there any case where a list can be null but have a size greater than 0? Or is this redundant and equivalent to if (xyzList.size() > 0)?
EDIT: xyzList can be modified from an outside class, so the null check is definitely needed. Thanks for responses, I've just had a long day and my mind was not functioning.
The code is ensuring that xyzList is not null before calling size() on it which would result in a crash/exception.
Because of short circuit evaluation, size() will not be called in the if clause when xyzList is null
An object must exist before you can dereference anything on it. This is what is being got at with the null-check: we want to be sure that xyzList exists before we start doing anything on it.
That said, depending on where it was declared, this check may be frivolous.
If you see this on a field that is declared final, then the field could be considered eagerly initialized, and because it's final, you could guarantee that it will never get set back to null.
private final List<XYZ> xyzList = new ArrayList<>(); // guaranteed not null
If you see this in a method, and there are no mutations to the variable at all to set it to a null value, then the null check is pointless, as again - it is not going to change for the lifecycle of that method.
public void someMethod() {
List<XYZ> xyzList = new ArrayList<>();
// do other operations without reassigning xyzList
// null check is useless since the variable is initialized to
// a non-null value
if(xyzList != null && !xyzList.empty()) {
// operation with list
}
}
This sort of pattern is done on variables which are not guaranteed to be initialized. If you're eagerly initializing a variable or field, then there's no need to perform this check.
If do some things with the list does not involve setting it to null, then the null check is redundant. A good IDE will spot this while you type and warn you of it.
Otherwise the null check ensures that the size check does not produce a NullPointerException.
I am not sure what
............................
do some things with the list
............................
is doing, but my guess is that "xyzList != null && xyzList.size() > 0" are called together because you don't want to end up calling a method on a null reference. Hence, it is not redundant
An Array list can't be NULL & 0 at same time.
But it doesn't meant that a not null array list always have size > 0.
Array list which is Not Null, can also have size 0.
Always ensure that ArrayList is not null before calling arrayList.size(), to avoid null pointer exception.
example:
if (workImageArrayList != null) {
Toast.makeText(this, "size : " + workImageArrayList.size(), Toast.LENGTH_SHORT).show();
//can show ---> size : 0, but its not null.
} else {
Log.e("WorkImageArrayList", "" + workImageArrayList);
//arraylist is null.
}
This line construct a new empty ArrayList object with size = 0 and make the xyzList pointer points to that object.
List<XYZ> xyzList = new ArrayList<>();
xyzList pointer is null when it does not point to any object.
List<XYZ> xyzList;
Therefore, an ArrayList can either be null or have a size > 0, not both
Here's my code:
if (!quizDescs[0].isEmpty()) {
mDescText.setText(quizDescs[0]);
} else {
mDescText.setVisibility(View.INVISIBLE);
}
So, when this code runs, and the if condition returns true, everything is fine and dandy, however, if it returns false, it says there's a NullPointerException, and points me to the line of code containing the if statement.
Am I checking the condition right? Why is it returning a NullPointer?!
ANSWER:
if (quizDescs[0] == null) {
mDescText.setVisibility(View.INVISIBLE);
} else {
mDescText.setText(quizDescs[0]);
}
if quizDesc[0] is String, you can do
if(!StringUtility.isEmptyOrNull(quizDesc[0])){
mDescText.setText(quizDescs[0]);
}else {
mDescText.setVisibility(View.INVISIBLE);
}
By the way,
Null and being empty is not same
Consider
String s; //Initialize to null
String a =""; //A blank string
Its always a good practise to use
try{
//Your code here..
}catch(Exception e){
e.printStacktrace();
}
If either quizDescs or quizDescs[0] are null, you'll get a NullPointerException.
Obviously, if isEmpty() returns false, it means that isEmpty() was executed, so quizDescs[0] is not null when the condition returns true, and that's why it works.
Either make sure that both quizDescs and quizDescs[0] is never null, or change the condition to :
if (quizDescs != null && quizDescs[0] != null && !quizDescs[0].isEmpty()) {
....
} else {
....
}
You have an error because quizDescs is Null so when you try to get quizDescs[0] in the condition, you try to get the first item of null object.
The only possible ways the if-line can cause a NullPointerException, is when quizDescs itself is null or the first element quizDescs[0] is null. Try to extract quizDescs into a local variable for debugging purposes and inspect its content.
You can either initialize your array with empty strings or add a check for null - or better review your logic how null is a possible condition. Usually null values should be avoided (see Bloch, Effective Java 2nd Edition, item 43 for a similar case).
I'm using a method that returns a list that is fetched from a web service. This list sometimes does not contain anything. Which results in "java.lang.IndexOutOfBoundsException"
ArrayList<String> placesList = osm.getPlace(poi, listingCity, listingState);
if (placesList != null)
{
poi = placesList.get(0);
poiStreet = placesList.get(1);
}
I have used the if statement above to prevent the exception, but it does not work. Is there anyway I can prevent this Exception by using if statements so the program do something else in case the list is empty?
If you want to ensure the list is not null, and, contains at least two elements, do this:
if( placesList != null && placesList.size() >= 2)
The list could be defined, but have no strings in it (an empty list). You should also check the size of the list:
ArrayList<String> placesList = osm.getPlace(poi, listingCity, listingState);
if (placesList != null && placesList.size() > 1)
{
poi = placesList.get(0);
poiStreet = placesList.get(1);
}
The list object is not null, but the contents inside can be zero
Use placeList.size() to check the number of contents inside.
If ArrayList == null returns true it doesn't mean that it's empty, it means that it hasn't been initialized and it points to null.
In order to check if your list is empty, you can use
if (!placesList.isEmpty()){
}
Just because the ArrayList object is not null, does not imply there are any elements in it.
You can call isEmpty() or size() methods to determine if there are any elements in the array.
Try this:
ArrayList<String> placesList = osm.getPlace(poi, listingCity, listingState);
if (placesList != null && placesList.isEmpty() == false )
{
poi = placesList.get(0);
poiStreet = placesList.get(1);
}
Javadoc reference
Check to make sure the ArrayList is not null, then add a second condition ensuring the size is equal to 2 to ensure it contains what you expect
if (placesList != null && placesList.size() == 2)
Try
if (placeList.size() > 1)
you should check length of the arraylist.
something like
if (placesList.size() > 0)
One way to approach this is by:
if(placesList.isEmpty())
{
//do something here when empty
}
else
{
poi = placesList.get(0);
}
I have the following code within a for loop to see if a string equals a search string:
if(Data.coord[i].equals(Data.search))
I've tested the code with exact values i.e if 1=1 and the rest of the code works fine. It just doesn't like the string comparison. The consol gives out this error:
Exception in thread "main" java.lang.NullPointerException
at highercoursework.Search.main(Search.java:16)
at highercoursework.Main.main(Main.java:16)
Thanks
You should compare the constant to your parameter since it can be null.
For example if Data.search is a constant which you are searching for you should do this:
if(Data.search.equals(Data.coord[i]))
In this case you won't end up trying to call methods on a null reference and you won't need unnecessary null checks either.
You have an unpopulated element in your array i.e.
Data.coord[i]
is null. Note that Data.search could be null, but the equals() method will handle this. You just need to perform the lement check first.
String[] coord = new String[100];
This will mean you can assign something to coord[0] but until you do that coord[0] is null. Hence the null pointer exception.
You can try.
String data= Data.coord[i];
if(data != null && data.equals(Data.search))
you can avoid your problem in two ways:
In the case coord[i] should not be null
if (Data.coord[i] != null) {
if(Data.coord[i].equals(Data.search)) {
}
} else {
logger.error("Unexpected Behavior: coord[i] should not be null");
}
Note: You can replace the logger message by a more appropriated code that fit to your requirement.
In the case your your coord[i] can be null
comparing in this way won't throw an exception if Data.coord[i] is null. (Assuming Data.search is a constant and can't bu null) So the rules for this case is: use in priority a String object constant to call the method equals.
if (Data.search.equals(Data.coord[i])) {}
Read this to understand What is a Null Pointer Exception?
if coord[] is initialized properly, value of Data.coord[i] may be null. You can check
if(Data.coord[i] != null && Data.coord[i].equals(Data.search)) {}
Try this:
if(DATA != null && Data.coord[i].equals(Data.search))