Defining Array

Java 8
int arr1[] = new int[3];

int[] arr2 = new int[3];

int[] arr3 = { 1,2,3 };

Array is a container for a sequence of a fixed number of items.

In Java, the length of the Array should be specified in its declaration, and it cannot be changed afterward.

All arrays in our example will have a length 3, but for the arr3 we are literally specifying its values.


Array Length

Java 8
int[] arr = { 1,2,3 };

int length = arr.length;  // 3

The length property returns the length of an Array.


Get Element at index

Java 8
String[] animals = {"Cat", "Dog", "Cow"};

String cat = animals[0];  // Cat

Array elements can be accessed by their index.

In Java, the Array Index starts from 0.


Set Element at index

Java 8
String[] animals = {"Cat", "Dog", "Cow"};

animals[0] = "Lion";

Here we are setting an element at index 0 to a value Lion.

So now animals array values are Lion, Dog, Cow.


Append Element

Java 8
int[] arr1 = { 1,2,3 };

int[] arr2 = new int[arr1.length + 1];

for (int i=0; i<arr1.length; i++)
  arr2[i] = arr1[i];

arr2[arr1.length] = 4;

In Java, after we create an array, we cannot change its length.

So to have something similar to appending an element to the end of an array, we need to create a longer array.


Find Element

Java 8
String value = "Dog";
String[] animals = {"Cat", "Dog", "Cow"};

int index = -1;

for (int i=0; i<animals.length; i++) {
  if (animals[i] == value) {
    index = i;
// index -> 1

There is no direct builtin method on Arrays to search for a value in an Array.

Here we are searching for the value Dog in the animals array.


Get SubArray

Java 8
String[] animals = {"Cat", "Dog", "Cow"};

String[] sub =
    Arrays.copyOfRange(animals, 2, 3); // {"Cow"}

The copyOfRange() method on the Arrays class gets the starting index (inclusive) and ending index (exclusive) and returns the SubArray for those parameters.


Sort Array

Java 8
int[] arr = {2, 4, 3, 1};

java.util.Arrays.sort(arr);  // arr -> {1,2,3,4}

The sort() method on the Arrays class sorts an Array in Ascending order.

There is not a best builtin way to sort an Array in reverse in Java, but if your array elements are not Primitive, you can do this:

Integer[] arr = {2, 4, 3, 1};

// arr -> {4,3,2,1}

Convert to String

Java 8
String[] animals = {"Cat", "Dog", "Cow"};

String str = java.util.Arrays.toString(animals);
// str -> "[Cat, Dog, Cow]"

The toString() method on the Arrays class returns a string representation of an Array.