I am trying to create an array of a custom object and I think the error I'm running into is that the objects within the array are not initialized prior to use (its a run time error, so i'm not entirely sure). The part that doesn't make sense is, if something hasn't been initialized before it is used, wouldn't the java compiler complain?

I have so far figured out how to create and allocate memory for the array (portfolio is my custom class) using;

private Portfolio[] c_port = new Portfolio[9];

As far as initializing it, I haven't come up with or been able to find anything other than simple class initializations like "int" online anywhere.

My Portfolio class is as follows;

public class Portfolio {
    private int numStocks = 0;
    private String stockName;
    
    public void Portfolio(){
        numStocks = 0;
        stockName = "Default Stock Name";
    }

    public void changePortfolio(String purchaseStock, int num_stocks){
        numStocks+= num_stocks;
        stockName = purchaseStock;
        System.out.print("In changePortfolio\n");  //tattle statement
        
    }
    
    public int ownedStocks(){
        return numStocks;
    }
    
    @Override
    public String toString(){
        return "[" + numStocks + " shares of " + stockName + "]";
        
    }
}

I'm hoping this is something simple that I'm just missing due to inexperience with the language. Thanks in advance for your help!

new Portfolio[9]
Creates an array of 9 references to instances of class Portfolio. Initially all those references are null. That's why you get a Null Pointer Exception if you try to use them.
In theory the compiler could identify at least some of the cases where that could happen, but in general its just too hard.
What you need to do is to initialise each element of the array (reference) by giving it an actual instance of Portfolio to refer to.
In the simplest case that's just

for (int i = 0; i < c_port.length; i++) {
    c_port[i] = new Portfolio();
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.