1. Array Declarations
Declaring an Array
We learned about variables already, such as int x = 5;
, where x stores one number. An array is a variable that can store more than just one value. The syntax for an array is like so:
public class MyProgram { public static void main(String[] args) { //Let's create an array with the values 10,20,30,and 42 int[] x = {10,20,30,42}; //Read "int array x equals the array of 10,20,30,42" //Another way to declare an array with initial values: int[] x = new int[]{1,2,3,4,5}; //Let's create another array, y, with 5 zero's: int[] y = new int[5]; //also works for other types like double[] y = new double[5]; } }
As you can see in the above example, there are three types of Java array declarations:
- Declaring the array with initial values. TYPE[] varname = {VAL1,VAL2,VAL3}; This declaration must be used as a statement on its own line
- Declare the array equal to an array expression. TYPE[] vartwo = new TYPE[]{VAL1,VAL2,VAL3}. This has an advantage in that the right hand side can be used as part of a larger expression. In other words "new TYPE[]{X,Y,Z}" is an array expression in the same way that (1+2) is an int expression.
- Declare an array equal to an empty array expression. TYPE[] varthree = new TYPE[initial_size]. Unlike C and C++, Java sets each item in the array to its default value. For numeric primitives (byte, short, int, long, float, double), the default value is zero. For char, the default value is the "null character", which is equal to (char)0. For booleans, the default value is false. Finally, for Objects such as strings, the default value is "null". We will learn more about null later.
Because Java initializes arrays with values, creating new arrays can take a lot of time. Unlike C and C++, creating an array of size 1000 will cause Java to initialize 1000 elements.
Java arrays cannot be resized. To resize an array, you must create another array of a different size and copy the elements over to the new array. We will learn about the resizeable List class in a later section.