0

I get a null pointer exception for this statement.

accountList.getTrxnList().getTrxns().size() > 0

accountList is a list of accounts I get from an external API call. And I am sure that a non-null accountList value is returned.But I am not confident about getTrxns() has any values. So before processing I check whether there are any Trxns but this also results in a null pointer exception.

This is my model class

public class AccountList{

    private TrxnList trxnList;

    public static class TrxnList {

        private List<Trxn> trxns;

        public List<Trxn> getTrxns() {
            return trxns;
        }
    }
}

Can someone please point out why this is raising nullpointer exception? I did some research on this so I cannot understand this raising nullpointer exception even if there are no items in trxns List.

Thank you.

Ran_Macavity
  • 154
  • 2
  • 21

3 Answers3

4

Your List is not instantiated, only declared. You need to put:

private List<Trxn> trxns = new ArrayList<>(); 
yur
  • 380
  • 2
  • 15
Ssr1369
  • 348
  • 3
  • 16
  • 1
    Must be `new ArrayList<>()` – bathudaide Nov 05 '19 at 08:51
  • That's if you want to create an ArrayList, but then you'd declare the variable of type ArrayList too, right? – Ssr1369 Nov 05 '19 at 08:53
  • 1
    Thanks for your answer @Ssr1369. accountList= jaxbConfig.unmarshal(result, AccountList.class); Actually I unmarshal to get my object. Other variables are not instantiated as well and they do not give an error.That is my problem. – Ran_Macavity Nov 05 '19 at 08:54
  • As a good practice, you should always make sure everything's instantiated properly. So, as a general rule, if you don't use a constructor, I'd add to the getter "if(trxnList==null) trxnList=new List<>();" before returning it. – Ssr1369 Nov 05 '19 at 08:58
  • 1
    @Ssr1369 Off-Topic, but yes you can instantiate a list as ```private List list = new ArrayList<>();```. Actually you must, because ```private List list = new List<>();``` causes a compiler error ```Cannot instantiate the type List```. – yur Nov 05 '19 at 09:47
2

You could also catch the NullPointerException, but I do agree with the other commenter that the exception is resolved by instantiating the List.

public class AccountList{

    private TrxnList trxnList;

    public static class TrxnList {

        private List<Trxn> trxns;

        public List<Trxn> getTrxns() {
            try
            {
                return trxns;
            }
            catch(NullPointerException e)
            {
                // handle the list==null case here
                // maybe instantiate it here if it's not:
                trxns = new ArrayList<>();
            }
        }
    }
}
yur
  • 380
  • 2
  • 15
1
public class AccountList{

    private TrxnList trxnList;

    public static class TrxnList {

        private List<Trxn> trxns;

        public List<Trxn> getTrxns() {
            return Optional.ofNullable(trxns).orElse(new ArrayList())
        }
    }
}