Java is quite a strict language when it comes to array types, sizes and assignment. For those just starting out with Java, the way in which variables work can be rather difficult to understand compared to other languages such as Python or PHP, this difficulty extends to the use of arrays and their often tedious nature.
Re-defining an array's size in Java
The size of an array in Java is set when it is first defined, it creates a set amount of elements, each of which can hold a single value of a given type. When assigning values to the elements, you cannot exceed that initial size.
If you do need to increase the size of an array, you will essentially need to create a whole new array of the desired size, then copy the values from the previous array into the new one.
There are a couple ways you could accomplish this tasks. One of the more simple ways would be to assign the old array's values to a temporary variable, then redefine the array with the desired size and copy the values into it. You can then add any extra values into the new array that you couldn't before due to the size constraint.
// our initial array
int[] testArr = new int[ 2 ];
testArr[ 0 ] = 1;
testArr[ 1 ] = 2;
// store the array's values in a temporary variable and redefine its size
int[] temp = testArr;
testArr = new int[ 3 ];
// copy the values of the old array into the new one using a loop
for( int i = 0; i < temp.length; i++ ){
testArr[ i ] = temp[ i ];
}
// add any extra values
testArr[ 2 ] = 3;
It can be quite long-winded to use such methods. If the situation allows for it, you can also consider Java's built in ArrayList objects which do not have a fixed size and can more easily be modified.
Re-defining an array's values (and size) using shorthand assignment
If you want to assign values to an array as soon as it is defined, you can make use of the shorthand array assignment statement. This is also a great way to redefine an array's length as it derives the size from the given amount of elements.
// define your initial array
int[] testArr = new int[]{
1, 2, 3
};
// redefine the array with different values
testArr = new int[]{
5, 4, 3, 2, 1
};
This method is more useful for small arrays whose values don't change much, but it does have its place. For example, this could be used for a re-usable query for use in an HTTP request.
If you have any questions feel free to leave a comment below!