Java – Arrays

An array is a collection of variables of the same type. When you need to store a list of values, such as numbers. You can store them in an array, instead of declaring separate variables for each number.

int[ ] arr = new int[4];

The above code is 4 array. In an array, the elements are ordered and each has a specific and constant position, which is called an index.

Initializing Arrays

Sometimes you might see the square brackets placed after the array name, which also works, but the preferred way is to place the brackets after the array’s data type.

String[ ] myNames = { "A", "B", "C", "D"};
System.out.println(myNames[2]);

// Outputs "C"

Array Length

access the length of an array (the number of elements it stores) via its length property.

int[ ] intArr = new int[4];
System.out.println(intArr.length);

//Outputs 4

The for loop is the most used loop when working with arrays. As we can use the length of the array to determine how many times to run the loop.

int [ ] myArr = {8, 2, 1, 5};
int sum=0;
for(int x=0; x

Multidimensional Arrays

Multidimensional arrays are array that contain other arrays. The two-dimensional array is the most basic multidimensional array.

Example:

int[ ][ ] sample = { {8, 9, 0}, {6, 7, 8} }; 

This declares an array with two arrays as its elements. To access an element in the two-dimensional array, provide two indexes, one for the array, and another for the element inside that array.

int x = sample[1][0];
   System.out.println(x);

//output
6

There is also a “for-each” loop, which is used exclusively to loop through elements in arrays:

Syntax:

for (type variable : arrayname) {
...

}

The following example outputs all elements in the site array:

public class MyClass {
  public static void main(String[] args) {
    String[] site = {"Google", "Youtube", "Facebook", "Baidu.com"};
    for (String i : site) {
      System.out.println(i);
    }    
  }
}
Related Post