0

I wrote some classes in Java but when I run the program I receive the error "ArrayIndexOutOfBoundsException", the incriminate class is this:

public class Bank {

    private String name;
    private int maxbankaccount;
    private int activebankaccount;
    private String radice = "IT8634";
    private Conto[] bankaccount = new Conto[maxbankaccount];

    public void addconto(String cf) {
        bankaccount[activebankaccount] = new Conto(radice + activebankaccount , cf);
        activebankaccount++;
    }

    public Bank(String name, int maxbankaccount) {
        this.name = name;
        this.maxbankaccount = maxbankaccount;
    }
}   

I wrote a tester class to test :

public class TestBank {

    public static void main (String[] args) {

        Bank b1 = new Bank("Fidelity", 10);

        b1.addconto("PROVA");
    }
}

Since I didn't seem to have made logical errors using the array I debugged, I realized that in the creation of the array of objects the maxbankaccount variable isn't 10 (value passed in Test) but as default value (0),then I tried passing 10 directly and it works good. Why is not the value 10 of maxbankaccount passed but 0?

RAGHHURAAMM
  • 1,099
  • 7
  • 15
Fabio
  • 336
  • 3
  • 17
  • Possible duplicate of [Are fields initialized before constructor code is run in Java?](https://stackoverflow.com/questions/14805547/are-fields-initialized-before-constructor-code-is-run-in-java) – Slaw Oct 18 '18 at 17:37

3 Answers3

4
private Conto[] bankaccount = new Conto[maxbankaccount];

This initialization takes place before the rest of the constructor runs.

Move it into the constructor:

public Bank(String name, int maxbankaccount) {
    this.name = name;
    this.maxbankaccount = maxbankaccount;
    this.bankaccount = new Conto[maxbankaccount];
}
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • Further, if you were to declare the `maxbankaccount` field as `final` then you would get a compiler error to protect you against pre-initialized usage bug. – flakes Oct 18 '18 at 17:33
1

You have indeed made a logical error. The array bankaccount is getting initialized when the class is instantiated and is always 0.

Move it into the constructor and initialize it.

public Bank(String name, int maxbankaccount) {
    /* ... */
    this.bankaccount = new Conto[maxbankaccount];
}
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
0

Further more than the issues that are in the other answers, this

private int activebankaccount;

does not initialize the variable activebankaccount So in:

public void addconto(String cf) {
    bankaccount[activebankaccount] = new Conto(radice + activebankaccount , cf);
    activebankaccount++;
}

you are using an uninitialized vale as index of the array bankaccount

forpas
  • 160,666
  • 10
  • 38
  • 76