2

I am new to java, I am trying to add an object to an array of objects. I have 2 Class, Bank and Account. Bank contains an array of Accounts objects.

Bank constructor initializes the Accounts array.

public Bank (String bankName, int num) {

        nameOfBank = bankName;
        max = num;
        Account[] accounts = new Account[max];
        count = 0;

This is my addAccount method.

public boolean addAccount (Account acct) {
        if(acct == null) {
            return false;
        }

        accounts[count++] = acct;
        return true;
    }

This is how I add the account in main

newBank.addAccount(test);

ps. I am not allowed to use anything other than java array.(no arrayList)

Exception in thread "main" java.lang.NullPointerException
        at Bank.addAccount(Bank.java:55)
        at TestBank.main(TestBank.java:15)

1 Answer 1

9

You've defined accounts as a local variable to the constructor, not a class level member.

public class Bank {
    Account[] accounts;
    int count;

    public Bank(String bankName, int num) {
        accounts = new Account[num];
        count = 0;
    }

    public boolean addAccount(Account acct) {
        // Do your work
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

sorry, I have private Account[] accounts; as a variable
@user2387963 - It doesn't matter if you have it or not, based on the code in your constructor you are declaring and initializing a local variable with the same name rather than your class level variable.
oh, so no need for Accounts [] accounts
@user2387963 No... you still need to declare Account[] accounts, but you need to declare it in the right place. Originally, you declared it as a local field within your constructor. Once you're out of the constructor, the field is out of scope and you can no longer reference it. If you declare accounts in your class (outside of any methods), then it's available to all methods in your class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.