Reputation: 167
When I try to push an element into a Java array where I take the array size from a constructor argument, it throws an ArrayIndexOutOfBoundsException
exception. However, when I set the size while declaring the array adding an element works.
Here is my code:
public class Stack {
public int size;
public Stack(int size)
{
this.size = size;
}
public int[] arr = new int[size];
public int top = -1;
// Methods
public void push(int value)
{
top++;
arr[top] = value;
}
}
The following throws the exception:
new Stack(10).push(123);
Upvotes: 8
Views: 231
Reputation: 14968
You need to initialize the array when the value of this.size
is the "correct" one. Initially the value of this.size
is 0
(zero) (see Initial Values of Variables) so this is not the time of initializing the array; you must "wait" in order to know what's the size the array will have. Where that size is provided? In the class constructor.
So it is inside the constructor where you have to initialize the array (with the provided size).
For example, see below commented code (yours):
public class Stack {
public int size ; // size = 0 at this time
public Stack(int size)
{
this.size = size;
}
public int[] arr = new int[size]; // still size = 0 at this time!
// so you're creating an array of size zero
// (you won't be able to "put" any value in it)
public int top = -1;
//Methods
public void push(int value)
{
top++; // after this line `top` is 0
arr[top] = value; // in an array of zero size you are trying to set in its
// "zero" position the value of `value`
// it's something like this:
// imagine this array (with no more room)[], can you put values?,
// of course not
}
}
So, in order to fix this you need to change your code like this:
public class Stack {
public int size;
public int[] arr; // declare the array variable, but do not initialize it yet
public int top = -1;
public Stack(int size) {
this.size = size;
arr = new int[size]; // when we know in advance which will be the size of the array,
// then initialize it with that size
}
//Methods
public void push(int value) {
top++;
arr[top] = value;
}
}
Upvotes: 7