Java Array

An array is a group or the collection of data having the same data-type. Arrays are objects in Java and with the fixed size(disadvantage). Elements are arranged inside the array with index numbers starting from zero as the first elements.
Random access of any element present in the array and code optimization feature makes it more useable.

Types of array:

  • Single Dimensional Array. 
  • Multidimensional Array 

One Dimensional Array: 

One-dimensional array in Java is an array with a bunch of values that are declared with a single index.

Array declaration:

Example:

An array declaration has two components:
The type that is the data-type of an element and the name that is given by user choice with the brackets[].

Array initialization:

To initialize an array new is used and it appears as follows:

Example:

We can also set by combining declaration and initialization in the following ways:

Accessing an array element:

Array elements can be accessed by using its index number, where each element is assigned by one index number.
Example:


Multidimensional Array(Jagged Arrays): 

Declaring an array of arrays is known as Multidimensional Array or Jagged Arrays. In simple words, it is an array of arrays. It is created by appending a square brackets “[]” for each dimension. Here data are stored in a tabular form that is in row-major order.

Syntax:

Declaration:

Instantiate Multidimensional Array in Java:

Array initialization:

We can also declare and initialize the 2D array together:


Passing Array to Methods:

Similar to a variable, an array can also be passed to methods. To pass an array users need to call the array with its name and without the square roots within the method call. Let us see with an example below:

Example: To sum the array values

Output:


Returning Arrays from Methods:

As array can be passed to methods, it can also be returned from the array.
The following shows an example of it.

Output:

The foreach Loops:

It is also possible to print the array using its for-each loop. for-each loop prints the array elements one by one, by holding an array element in a variable, then executing the body of the loop.

Example of foreach loop:

Output: