javaarraylistobjectinstantiation

unable to instantiate a user defined class in java


I am unable to instantiate a user defined class. I am writing a servant class for RMI server wherein I am trying to instantiate another class. PFB a small extract of my code

public void subscribe(String user, String stockSym)throws RemoteException {
    try{
           System.out.println("In the servant");
           StockUser s = new StockUser(user, stockSym);
           System.out.println("In the servant2");
           System.out.println("In the servant1");
           ......
      }

subscribe --> a method of my servant class

StockUser --> the user defined class that I am trying to instantiate

It is simply skipping the rest of the lines from the line StockUser s = new StockUser(user, stockSym);. Even with a try-catch I am unable to capture any exception. If I comment StockUser s = new StockUser(user, stockSym); line out then all the rest of the lines are getting executed. The variables userand stockSym are being correctly populated and are not NULL. Can someone please tell me what might be the problem?


Solution

  • stockSym.add(stock) would give you NullPointerException, since you don't initialize stockSym.

    public StockUser(String userName, String stock) 
    { 
        stockSym.add(stock); // exception here
        this.userName = userName;
        id++; 
    }
    

    You must initialize this list :

    public StockUser(String userName, String stock) 
    { 
        stockSym = new ArrayList<String>();
        stockSym.add(stock);
        this.userName = userName;
        id++; 
    }