1

I am relatively new to java, and this is only the second time I have ever tried to design a program that has an array of class objects. I am having trouble because when I go into debug mode, it is showing me that the arrays are being built correctly. However, when I try to build a string or even print to the console, I am getting a null pointer exception.

I am trying to make an array of Slot class objects.

public class C {
int slotNum;
Slot[] s;


public C(int byteSize, int slotNum){
    this.slotNum = slotNum;

    Slot[] s = new Slot[slotNum]; //create an array of slots

    for(int i = 0; i < slotNum; i++){ //for every slot and instantiate
        s[i] = new Slot(byteSize); 
    }
    display();
}

And the Slot class has its own array, block[], constructed by a value passed in through its constructor.

public class Slot {

boolean v;
short block[];

public Slot(int byteSize){
    valid = false;

    //Instantiate each element in block[] to 0
    short block[] = new short[byteSize];
    for(int i = 0; i < block.length; i++){
        block[i] = 0;
    }
}

Later in the program I then try to print to the console or build a string and it always breaks when I try to use any element in the slot[] in the C class.

Have I instantiated and initialized my 2 different arrays correctly?

1
  • No you are just initializing the local arrays that you make in the constuctor Commented Oct 18, 2015 at 20:14

3 Answers 3

1
public class C {
int slotNum;
Slot[] s;


public C(int byteSize, int slotNum){
this.slotNum = slotNum;

s = new Slot[slotNum]; //create an array of slots

for(int i = 0; i < slotNum; i++){ //for every slot and instantiate
    s[i] = new Slot(byteSize); 
}
display();
}

Try something like these instead

public class Slot {

boolean v;
short block[];

public Slot(int byteSize){
valid = false;

//Instantiate each element in block[] to 0
block = new short[byteSize];
for(int i = 0; i < block.length; i++){
    block[i] = 0;
}
}
Sign up to request clarification or add additional context in comments.

1 Comment

It worked... I can't believe something so simple tripped me up for so long. Thank you!
1

Replace

short block[] = new short[byteSize];

with

block = new short[byteSize];

Comments

0

Always use a this operator to initialize in a constructor so that you may differentiate clearly between local variables and instance variables

public Slot(int byteSize){
    valid = false;

    //Instantiate each element in block[] to 0
    this.block = new short[byteSize];
    for(int i = 0; i < block.length; i++){
        block[i] = 0;
    }
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.