I have below code in apex constructor of the controller where it shows null pointer exception. Can someone please let me know if I have issues with declaration and also the workaround.

 for(Userterritory ut: [select territoryid from userterritory where userid in : resultIds])
        { system.debug(ut.territoryid);

Please userterrsids is a set of Id which is public and declared with gettter setter as below.

public set<ID> userterrsids {get;set;}

2 Answers 2


You could define the property in the following way to avoid getting a null pointer exception -

public set<Id> userterrsids {
    get {
        if(userterrsids == null) {
            userterrsids = new Set<Id>();
        return userterrsids;

You have to initialize a variable somehow before you use it. In this case, userterrsIds is null, so "add" doesn't have anywhere to add the values to. The easiest way to do so from where you're at is to simply initialize it right before the loop:

userterrsids = new Set<Id>();
for(...) {

If you have a constructor for the class, consider initializing it there, since that's the point of a constructor. A proper constructor will make sure that all variables are set to a not-null value, if appropriate.

  • Can you please let me know how to initialize in the get set while declaring the Set<ID> as public. I remember such a thing I found earlier but can't find it now over google search. Commented Dec 4, 2016 at 9:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .