Day 6: Arrays and Array Methods in Java

Day 6: Arrays and Array Methods in Java

ยท

5 min read

Arrays are a fundamental data structure in Java that store a fixed number of elements of the same data type. They are useful when you want to store multiple values of the same type and access them by using an index.

Declaring Arrays

You can declare an array by specifying the data type of its elements, followed by square brackets [ ]. For example, to declare an array of 5 integers:

int[] nums = new int[5];

This creates an array named nums that can hold 5 int values. By default, the values in the array are initialized to 0.

You can also initialize the array with values directly:

int[] nums = {1, 2, 3, 4, 5};

To access elements of the array, use the index inside square brackets. For example:

int first = nums[0]; // first = 1
int second = nums[1]; // second = 2

The index starts at 0, so nums[0] refers to the first element, nums[1] refers to the second element, and so on.

You can also omit the new int[5] while declaring and initializing the array in one step:

int[] nums = {1, 2, 3, 4, 5};

However, once initialized, the size of the array cannot be changed.


Arrays of Other Types

You can have arrays of other primitive types like:

byte[] bytes;
short[] shorts;
long[] longs;
float[] floats;
double[] doubles;
char[] chars;

And also object types:

String[] strings;
Rectangle[] rectangles; // etc.

So arrays can hold data of any type in Java.


Array Length

You can find the length of an array using the .length property. For example:

int[] nums = {1, 2, 3, 4, 5};
int length = nums.length; // length is 5This is useful when you want to iterate over all elements of an array or access elements by index.

Iterating Over Arrays

You can iterate over an array using a for loop. For example:

int[] nums = {1, 2, 3, 4, 5};
for (int i = 0; i < nums.length; i++) {
    int num = nums[i];
    System.out.println(num);
}
// Prints 1 2 3 4 5

This loops from index 0 to length - 1 and prints each element.

You can also use an enhanced for loop:

for (int num : nums) {
    System.out.println(num);
}

This iterates over each element in the array and assigns it to the variable num, which you can then use in the loop body.


Accessing Elements

To access elements of an array, use the index inside square brackets [ ]. For example:

int first = nums[0]; // Access first element at index 0
int second = nums[1]; // Access second element at index 1

You can access elements like this:

nums[0] // First element
nums[1] // Second element
nums[2] // Third element
...
nums[nums.length - 1] // Last element

The index starts at 0, so nums[0] refers to the first element. Attempting to access an element at an invalid index will throw an ArrayIndexOutOfBoundsException.


Changing Elements

You can also change elements of an array by assigning new values to indexes:

nums[0] = 10; // Change first element to 10
nums[1] = 20; // Change second element to 20

So arrays in Java, once initialized, have a fixed size but the values of their elements can be changed.


Copying Arrays

To copy an array in Java, you can use the System.arraycopy() method. For example:

int[] original = {1, 2, 3};
int[] copy = new int[3];
System.arraycopy(original, 0, copy, 0, 3);

This will copy all 3 elements from the original array to the copy array.

You can also use the Arrays.copyOf() method:

int[] copy = Arrays.copyOf(original, 3);

This copies the first 3 elements of the original array to the new copy array.


Multidimensional Arrays

Java also supports multidimensional arrays - arrays of arrays. You declare a multidimensional array as follows:

int[][] matrix = { {1, 2, 3}, {4, 5, 6} };

This creates a 2D array with 2 rows and 3 columns. You can access elements like this:

matrix[0][0]; // 1
matrix[0][1]; // 2
matrix[1][2]; // 6

You can have up to 255 dimensions in a multidimensional array.


Arrays Class

The Arrays class in Java contains various static methods for manipulating arrays. Some useful methods are:

  • Arrays.toString() - Prints the string representation of the array. Useful for debugging.

  • Arrays.sort() - Sorts the array in ascending order.

  • Arrays.binarySearch() - Searches the sorted array for a given element.

  • Arrays.fill() - Fills the array with a given value.

  • Arrays.equals() - Checks if two arrays are equal.

  • Arrays.copyOf() - Copies elements from one array to another.

For example:

int[] nums = {3, 1, 2};
Arrays.sort(nums); // nums is now {1, 2, 3}
int index = Arrays.binarySearch(nums, 2); // index is 1

Arrays.fill(nums, 5); // nums is now {5, 5, 5}
Arrays.equals(nums, new int[] {5, 5, 5}); // true

So the Arrays class contains a lot of useful methods to work with arrays in Java.

In summary, arrays are a fundamental data structure in Java that store a fixed number of values of the same type. They can have one or more dimensions and their size is fixed once initialized. Arrays allow efficient access and manipulation of groups of values.

Did you find this article valuable?

Support Lexy Thinks by becoming a sponsor. Any amount is appreciated!

ย