10 Examples of Array Data Structure in Java

Here are some of the important properties of the array in Java:

  1. Unlike C and C++ array is an object in Java.

  2. The length attribute of the array gives the length of an array, this is different from the length() method of String.

  3. The length of an array is fixed and cannot be changed once created. The only way to increase or decrease length is to create a new array and copy the contents of an old array to a new array.

  4. You can access elements of an array using the index, which is non-negative integer value e.g. a[1] will give you second element.

  5. Array index starts at zero and ranges till length -1.

  6. Unlike C and C++ Java performs bound checks while accessing array elements. Trying to access an invalid index in the array will throw java.lang.ArrayIndexOutOfBoundsException.

  7. An array is typed in Java, you cannot store Integer in an array of String in Java. It will throw ArrayStoreException at runtime.

  8. You can create an array of both primitive and reference types in Java.

  9. Array elements are stored in the contiguous memory location, hence creating a big array of JVM may throw java.lang.OutOfMemoryError: Java heap space if that big chunk of memory is not available.

  10. The array is the backbone of many useful collection classes in Java e.g. ArrayList and HashMap both are backed by an array.


Now, let's see some examples of using an array in Java:


1) How to initialize an array in Java?

There are multiple ways to initialize an array in Java. You can only declare them or initialize them inline as shown below:

int[] primes = new int[10]; // elements will be initialize with default valueint[] even = new int[]{2, 4, 6, 8}; // inline initializationint[] odd = {1, 3, 5};

Si