1

So, I would say I'm pretty novice at programming and most of my background comes from C++, where I'm dealing with pointers and references and whatnot. I've started to learn Java, and I had to write this example program but for some reason I cannot escape the NullPointerException in the program. I tried searching for answers, and I understand the other answers I've seen but I can't see why I would have a null pointer. Thinking maybe I was coding it entirely wrong, I rewrote the program in C++, but it seems to work with no problems which just boggled my mind even more. I'm thinking it's possibly because of the way Java handles references, since there's no concepts of pointers and addresses.

If it would help at all, I could post the header/class and a stack dump as well.

package com.company;

import java.util.Random;

public class Main {

    public static void main(String[] args)
    {
        // Create some bank accounts.
        BankAccount[] accountsList = new BankAccount[5];
        // Create a list of random names.
        String[] namesList = {"Bob", "Alice", "John", "Matt", "Billy"};
        // Set all account names, and print initial balance.
        for (int x = 0; x < 5; x++)
        {
            accountsList[x].SetCustomerName(namesList[x]);
            System.out.println("Initial Balance // Account: " + accountsList[x].GetCustomerName());
            System.out.println("Balance: $" + accountsList[x].GetBalance());
            System.out.println();
        }
        // Conduct n rounds of simulated deposit/withdrawal transactions for each account.
        for (int rounds = 5; rounds < 0; rounds--)
        {
            for (BankAccount x : accountsList)
            {
                System.out.println("Transaction Inquiry // Account: " + x.GetCustomerName());
                x.DepositFunds(Math.abs(new Random().nextInt()));
                x.WithdrawFunds(Math.abs(new Random().nextInt()));
                System.out.println();
            }
        }
    }
}

The same program rewritten in C++ (compiles fine and runs no problem)

#include "BankAccount.h"
#include <iostream>
#include <cstdlib>
#include <ctime>

int main(int nArgs, char* pszArgs[])
{
    // Seed the RNG.
    srand(time(NULL));
    // Create some bank accounts.
    BankAccount accountsList[5];
    // Create a list of random names.
    std::string namesList[] = { "Bob", "Alice", "John", "Matt", "Billy" };
    // Set all account names, and print initial balance.
    for (int x = 0; x < 5; x++)
    {
        accountsList[x].SetCustomerName(namesList[x]);
        std::cout << "Initial Balance // Account: " << accountsList[x].GetCustomerName() << "\n";
        std::cout << "Balance: $" << accountsList[x].GetBalance() << "\n\n";
    }
    // Conduct n rounds of simulated deposit/withdrawal transactions for each account.
    for (int rounds = 5; rounds > 0; rounds--)
    {
        for (BankAccount &x : accountsList)
        {
            std::cout << "Transaction Inquiry // Account: " << x.GetCustomerName() << "\n";
            x.DepositFunds(abs(rand()));
            x.WithdrawFunds(abs(rand()));
            std::cout << std::endl;
        }
    }
    return 0;
}
d_ven0m
  • 13
  • 3
  • There is a bug somewhere in your Java code. There is absolutely no point in you spending your time writing similar code in C++ to fix the Java code. Instead, **really** read what you can find here regarding NPEs. Use a debugger. And beyond that: how do you think we would be able to help with input that is A) incomplete (we dont see the BankAccount class) B) not containing the exception stack trace. So: welcome to Stack Overflow, please spend some time at the [help] to learn how to write questions that we actually can help with. – GhostCat Apr 21 '17 at 08:25
  • I don't believe this duplicate is appropriate here. It's more to do with the difference between arrays in Java and C++, Request to reopen? – Bathsheba Apr 21 '17 at 08:25
  • the BankAccount's in your array are never instantiated. – kalsowerus Apr 21 '17 at 08:25
  • @GhostCat I wasn't intending to write similar code in C++ to fix the Java code. I knew there was a bug in my Java code, I was just trying to make sure I wasn't completely messing up. Coming from C++, and having the mindset in mind, I had thought that the code would be sound. I only rewrote it to make sure it was Java-specific and not just poor programming altogether. And I DID state I would gladly post the class and stack trace if needed. However, given the simplicity of the program I didn't want to clutter it with large amounts of code if the problem could've been solved without. Which it was – d_ven0m Apr 21 '17 at 08:34
  • Arrg, you are correct. Sorry, I didn't look closely enough ... up since 3 AM. And maybe a subconscious rejection of C++ kicked in. Nonetheless this is a DUP; I just need to find the right one. – GhostCat Apr 21 '17 at 08:37
  • 1
    Should be re-closed as DUP to http://stackoverflow.com/questions/1922677/nullpointerexception-when-creating-an-array-of-objects – GhostCat Apr 21 '17 at 08:38
  • Great spot. Closed it. Up since 3am? You debugging something like `if (a = b)`? – Bathsheba Apr 21 '17 at 08:40

3 Answers3

5
BankAccount[] accountsList = new BankAccount[5];

This doesnt't create objects to fill the array.

You must iterate over an array and create objects to fill it in.

for(int i = 0; i< accountList.length; i++) {
    accoutnList[i] = new BankAccount();
}

In other programming languages the construction of array also means that this array is filled, in java you create an array, but that doesn't mean that array is initialized with proper objects. Actually it holds null references, thus observed NPE.

zubergu
  • 3,646
  • 3
  • 25
  • 38
0

Unlike C++, Java supports zero length arrays. But that does introduce some construction overhead. You need to initialise accountsList itself by writing

BankAccount[] accountsList = new accountsList[5];

whereupon accountsList is a reference to the array object. Importantly, the elements in accountsList are set to null. You need to initialise each one yourself. Loosely, think of accountsList as a std::shared_ptr<std::array<std::shared_ptr<T>>> type.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • I think you might re-close as DUP to http://stackoverflow.com/questions/1922677/nullpointerexception-when-creating-an-array-of-objects – GhostCat Apr 21 '17 at 08:38
0

You need to first create the BankAccount object and then set its "customerName" property, otherwise you're invoking the method on a null object.

accountsList[x] = new BankAccount();
accountsList[x].setCustomerName(namesList[x]);

When you create the array you're not creating its own elements as well.

Davis Molinari
  • 741
  • 1
  • 5
  • 20