Javaexercise.com

What is Array In Java?

Array is a collection of similar type of elements which are contiguously stored into memory. Array starts from 0 index and goes to n-1 where n is length of the array. Array is an index based data structure, each element can be accessed using its index value and the first element stores at 0 index.

Java Array Syntax

data_type[] array_name = new data_type[size];
  • size denotes how many elements this array can hold.
  • Replace data_type according to the type of values the array will hold. E. g. data types are int, char, etc.
  • Replace array_name with the name of your array.
  • new keyword is used to create new array.

Example: Creating A New Java Array

If we want to create an array of int witnbsph size 5 then: For example

public class ArrDemo {
    public static void main(String[] args) {
        // Creating an array
        int[] arr = new int[5];
        // Accessing element using index
        int element = arr[0];
        System.out.println(element);
    }
}
Output:
0

Explanation:

This program prints 0 because while created array we did not initialized its elements, so it is initialized by default values. 0 is default value of int type.

Java Array Example: Initializing An Array

To initialize an array, we can assign new value to each element of the array. See the example below.

public class ArrDemo {
    public static void main(String[] args) {
        // Creating an array
        int[] arr = new int[5];
        // Initializing an array
        arr[0] = 10;
        arr[1] = 15;
        arr[2] = 2;
        arr[3] = 3;
        arr[4] = 40;
        // Accessing first element
        int element = arr[0];
        System.out.println(element);
    }
}
Output:
10


Another approach: we can also create a new array by initializing at the same time. See the example below.

public class ArrDemo {
    public static void main(String[] args) {
        // Creating an array and initializing as well
        int[] arr = {10,20,5,2,6};
        // Accessing first element
        int element = arr[0];
        System.out.println(element);
    }
}
Output:
10

Java Array Length

We can get length of an array by using length property. It is helpful to know, how many elements are there in the array? See the example below.

public class ArrDemo {
    public static void main(String[] args) {
        // Creating an array
        int[] arr = {10,20,5,2,6};
        // Length of array
        int len = arr.length;
        System.out.println("Array length is: "+len);
    }
}
Output:
Array length is: 5


Traversing Java Array

We can traverse array elements either by using for loop or for-each loop. See the example below.

Example: for loop to iterate array elements

public class ArrDemo {
    public static void main(String[] args) {
        // Creating an array
        int[] arr = {10,20,5,2,6};
        // Length of array
        int len = arr.length;
        System.out.println("Array elements are:");
        for(int i=0;i<len;i++) { // for loop
            System.out.print(arr[i]+" ");
        }
    }
}
Output:
Array elements are:
10 20 5 2 6

Example: for-each loop to iterate array elements

public class ArrDemo {
    public static void main(String[] args) {
        // Creating an array
        int[] arr = {10,20,5,2,6};
        // For-each loop
        System.out.println("Array elements are:");
        for(int el:arr) {
            System.out.print(el+" ");
        }
    }
}
Output:
Array elements are:
10 20 5 2 6

Note: In for-each loop we don’t need to specify length of the array.


Modifying Array Element:

We can modify array element by assigning new value to its index position. See the example below.

Example
public class ArrDemo {
    public static void main(String[] args) {
        // Creating an array
        int[] arr = {10,20,5,2,6};
        System.out.println("Array elements are:");
        for(int el:arr) {
            System.out.print(el+" ");
        }
        // Modifying third element of the array
        arr[2] = 100;
        System.out.println("\nNew Modified Array elements are:");
        for(int el:arr) {
            System.out.print(el+" ");
        }
    }
}
Output:
Array elements are:
10 20 5 2 6
New Modified Array elements are:
10 20 100 2 6


Java Multidimensional Array

Java supports multidimensional array also known as array of array. In such case, data is stored in row and column based index (also known as matrix form). See the example below.

Example to create multidimensional array
int[][] arr = new int[2][3]
  • First dimension specifies number of rows while second specifies number of columns.
  • Structurally we can understand it as a table(consisting of rows and columns).
Example:2-Dimensional Array
public class ArrDemo {
    public static void main(String[] args) {
        // Creating an array
        int[][] arr = {{10,20,5,2,6},{6,2,5,20,10}};
        System.out.println("Array elements are:");
        for(int i=0; i<2;i++) {
            for(int j=0;j<5;j++)
                System.out.print(arr[i][j]+" ");
                System.out.println();
            }
        }
}
Output:
Array elements are:
10 20 5 2 6
6 2 5 20 10

Note: To traverse 2-dimensional array elements, we used two for loops, first for traversing rows and second for columns.


Example: Modifying multidimensional array

We can modify array elements by assigning new values to the specified row and column index number. See the below example.

public class ArrDemo {
    public static void main(String[] args) {
        // Creating an array
        int[][] arr = {{10,20,5,2,6},{6,2,5,20,10}};
        System.out.println("Array elements are:");
        for(int i=0; i<2;i++) {
            for(int j=0;j<5;j++){
                System.out.print(arr[i][j]+" ");
            }
            System.out.println();
        }
        // Modifying array element:
        arr[1][3] = 100;
        System.out.println("Modified Array elements are:");
        for(int i=0; i<2;i++) {
            for(int j=0;j<5;j++){
                System.out.print(arr[i][j]+" ");
            }
            System.out.println();
        }
    }
}
Output:
Array elements are:
10 20 5 2 6
6 2 5 20 10
Modified Array elements are:
10 20 5 2 6
6 2 5 100 10


ArrayIndexOutOfBoundsException

Java throws an exception java.lang.ArrayIndexOutOfBoundsException if the index value of an array exceeds, or negative or equal to length of the array. See the example below.

Example:
public class ArrDemo {
    public static void main(String[] args) {
        // Creating an array
        int[] arr = {10,20,5,2,6};
        System.out.println("Array elements at 10th index:"+arr[10]);
    }
}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 5 at corejava/corejava.ArrDemo.main(ArrDemo.java:10)


Java Array Default Values

Type Default Value
int 0
boolean false
float/double 0.0
String null

Example: Array Default Value
public class ArrDemo {
    public static void main(String[] args) {
        // Creating integer array
        int[] arr = new int[2];
        System.out.println("Default values are:");
        for(int el:arr)
            System.out.println(el);
        // Creating boolean array
        boolean[] bol = new boolean[2];
        System.out.println("Default values are:");
        for(boolean el:bol)
            System.out.println(el);
        // Creating float array
        float[] farr = new float[2];
        System.out.println("Default values are:");
        for(float el:farr)
            System.out.println(el);
        // Creating String array
        String[] str = new String[2];
        System.out.println("Default values are:");
        for(String el:str)
            System.out.println(el);
    }
}
Output:
Default values are:
0
0
Default values are:
false
false
Default values are:
0.0
0.0
Default values are:
null
null


Exercise:

Let's try some exercises to understand array.

  1. Take an Array as input. Print sum of even and sum of odd elements.
  2. Take an Array as input. Print the largest element in the array.
  3. Take an array as input. For each element in the array is it is odd then convert it to the next even number.
  4. Take an array as input. Print difference of largest and smallest element of the array.
  5. Take an array as input. Print intermediate value in the array.