简体   繁体   中英

Null Pointer Exception on Array in Java

The following code is returning a NullPointerException in Java. Can anyone clarify my mistake?

public void deposit2()
{
    BankAccounts[] accounts2 = new BankAccounts[10];
    accounts2[3].deposit();
}
BankAccounts[] accounts2 = new BankAccounts[10];

is the same as

BankAccounts[] accounts2 = {null, null, null, ... null };  // (10 times)

You need to assign values to the elements of accounts2 (or, at least to element 3) before you attempt to dereference them.

Just declare it as you declared it in your code and after that use for loop to assign object reference to all index.

For example:

public void deposit2()
{
    BankAccounts[] accounts2 = new BankAccounts[10];
    for(int i=0;i<10;i++)
    {
        accounts2[i] = new BankAccounts();
    }
    accounts2[3].deposite();
}

BankAccounts[] accounts2 = new BankAccounts[10]; creates an object ie an array of bank accounts with 10 references that can point to 10 BankAccount objects,they are initailized to null , you need to create the actual bank objects , try this

BankAccounts[] accounts2 = new BankAccounts[10];

for(BankAccounts b:accounts2)//for each loop
{
b=new BankAccounts();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM