Hello guys!
In this post I will talk about arrays.
Stores a group of data items all of the same type. Is an object that must be instantiated separately. Once instantiated, the array object contains a block of memory locations for the individual elements. Can be different sizes. Declaring the array creates the reference variable.
The array is declared by specifying the type of data to be stored, followed by square brackets
dataType [] variableName;
int [] nums;
The brackets can be after or before the variable name
int nums [];
To instantiate arrays, we use new operator
Example:
int [] nums;
nums = new int[10];
10 is the size of the array.
We can also declare and instantiate in the same line:
int[] nums = new int[10];
We can obtain the length of an array by using the property length:
names.length <- will return 10
An array can be initialized when it is created
int[] nums = new int[] {1, 2, 5, 8, 15, 30};
Or can be initialized later:
int[] nums = new int[3];
nums[0] = 12;
nums[1] = 3;
nums[2] = 19;
Java compiler does not check to ensure that the bounds of the array is exceed, so you will have no error but the JVM does check at runtime and an exception will occur.
Arrays can be also multidimensional, with 2, 3 or more dimensions. You will use a pair of square brackets for each dimension.
For 2D arrays: [row][column]
char[][] board;
boar = new char[3][3]
board[1][1] = 'X';
board[0][0] = 'O';
board[0][1] = 'X';
To copy an array into another, you can't use = but you can use a method from System, called System.arraycopy
System.arraycopy(source, source position, destination, destination position, length)
You will copy from source, starting from source position, a number of length positions, to destination, starting from destination position.
This is all with arrays!
0 Comments