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
Related
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.
}
}
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).
my question is really, really simple, but everything I find online tells me I am doing it the right way - but I obviously misunderstood something.
I have a simple, simple Java ListIterator, which in a while-hasNext()-loop returns a null for next(). Here's the code with my comments on the debug state:
[...]
ListIterator<Role> rolesIterator = currentUser.getRoles().listIterator();
// rolesIterator is now: java.util.ArrayList$ListItr
while( rolesIterator.hasNext() ) {
Role roleObject = rolesIterator.next(); // extra step for debugging reasons
String role = roleObject.getName(); // NullPointerException - roleObject is null
[...]
In my thoughts, the loop should not be entered, if there is no next() object - that's why I check using hasNext(). What did I understand wrong, and what is the correct way?
There is a next element in the list, and this next element happens to be null. For example:
List<String> list = new ArrayList<>();
list.add("foo");
list.add(null);
list.add("bar");
The above list has 3 elements. The second one is null.
Fix the code that populates the list and make sure it doesn't add any null Role in the list, or check for null inside the loop to avoid NullPointerExceptions.
ListIterator documentation states that next():
Throws:
NoSuchElementException - if the iteration has no next element
Furthermore, you do the appropriate hasNext() check as the loop condition. So the obvious conclusion is that currentUser.getRoles() contains null elements. To fix [this part of] your code:
while( rolesIterator.hasNext() ) {
Role roleObject = rolesIterator.next();
if(roleObject != null)
{
String role = roleObject.getName();
[...]
}
I believe list can contain null values.
so the roleObject can be null.
I prefer the for loop approach (cleaner):
for (Role roleObject : currentUser.getRoles()) {
...
}
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))