In Java terms, an Array is a bunch of variables called components or elements containing values that have the same type. Arrays are data structures consisting of related data items of the same type.

Once created, Arrays are fixed-length entities where they remain the same length. however, a reference array may be reassigned to a new array of different lengths.

The Java Collections API provides class Arrays, which have a set of utility methods for manipulation of the java array.

Here are some of the key information about Java Arrays

  • In Java, types are divided into primitive types and reference types. Since Java arrays are objects, they are considered reference types.
  • The elements of an array can be a reference or primitive data type.
  • Arrays in Java are different than they work in other languages like C/C++.
  • Arrays of any type can be created and might have one or more dimensions.
  • In order to refer to a particular element in a java array, the name of the reference to an array and position number of the element is specified and here the array position number is generally called as element index.

Declaring and Creating Arrays

As we know, all Objects in Java must be created with keyword new.

For an array, typically the programmer specifies the data type of the array elements and the number of elements as part of array creation syntax that uses keyword new.

Below is the syntax for declaring array variables and creating an array, here size is nothing but specifying array size.

datatype[ ] arrayName = new datatype [size];

Below is an example to declare and create a string array in java of 5 elements.

String[] a = new String[5];

so as per the above array declaration, it consists of total array elements of 5 with string representation.

The above can also be done in two steps

String[] a;   // declaring an array variable

a = new String[5]; // creating and initializing an java string array

Another way of creating an array is by using Array Initializer.

Array Initializer is a comma-separated list of expression which is declared inside braces { }. In this scenario, the length of the specified array is determined by the number of elements declared inside curly braces{}.

Here is the example of intializing type int array,

int x[] ={40,50,60,70}

So if you need to access array elements specifically, then you can retrieve them using the index of type int. i,e. x[2] from above returns the array index value of the 2nd position, which will be 60 in the above case. Note that position in an array always starts with 0.

Note that each element array receives a default value as null for reference types, false for boolean elements, and zero for numeric primitive type arrays.

Dimensional Arrays

Arrays can be categorized into Single Dimensional Arrays (or One Dimensional array) and Multi-Dimensional Arrays.

Single Dimensional Array or One Dimensional Array

The typical declaration of a single-dimensional array is

type[] variableName;

So type declares the data type of the array and the variable name is used to identify the respective array.

int[] countArray;

In order to create and performing array initialization of a single-dimensional array, here is the syntax.

variableName = new type[size];

i,e, if you want to declare and create a single-dimensional at one go, here, is the way.

int[] countArray  = new int[5];

Combining all together, here is the java program that demonstrates a single-dimensional created array.

public class SingleDimensionalArray {

	public static void main(String[] args) {

		int[] countArray = new int[5];
		countArray[0] = 10;
		countArray[1] = 20;
		countArray[2] = 30;
		countArray[3] = 40;
		countArray[4] = 50;
		System.out.println("Count of Array Index 3 is: " + countArray[3]);
	}
}



Output:
Count of Array Index 3 is: 40

Multi Dimensional Arrays

Multi-Dimensional Arrays are nothing but arrays of arrays.

In order to declare a multi-dimensional array, you need to specify an additional array index using another pair of [].

The typical declaration of the multidimensional array is

int[][] multiCountArray;

i,e if you want to declare and create a dimensional on a single go, here is the way.

int[][] multiCountArray  = new int[3][4];

Here is the java program that demonstrates a multi-dimensional array.

public class MultiDimensionalArray {

	public static void main(String[] args) {
		int[][] multiCountArray  = new int[3][4];
		int a, b, c = 0;
		
		for(a=0; a < 3; a++)
			for(b=0; b < 4; b++) {
				multiCountArray[a][b] = c;
				c++;
			}
		
		for(a=0; a < 3; a++) {
			for(b=0; b < 4; b++) 
			System.out.println(multiCountArray[a][b] + " ");	
			System.out.println();
			}		
		
	}

}

Output:
0 1 2 3
4 5 6 7
8 9 10 11

Passing Arrays to Methods

In order to pass an argument of array type, specify the name of the array without [].

for example, array zipCodes is declared as below

int[] zipCodes = new int[5];

if the method and method signature is declared as below

public void retrieveValues(int[] codes);

then passing an array to the method will be as follows

retrieveValues(zipCodes);

As we know in Java, an array object aware of its own length and can process arrays internally(i.e. by the array length field). Hence, when we pass an array object to a method, it is not required to pass the length of the array as an argument.

Accessing Array Elements

In order to access an element of an array, we can retrieve using the index number.

Following is the syntax to retrieve an element of an array.

array[index];

Here is the example of accessing array elements using the index of an array.

public class RetrieveElements {

	public static void main(String[] args) {

		String[] countries = { "USA", "AUSTRALIA", "NEWZEALAND", "INDIA", "JAPAN" };

		System.out.println("First Element: " + countries[0]);
		System.out.println("Second Element: " + countries[1]);
		System.out.println("Third Element: " + countries[2]);
		System.out.println("Fourth Element: " + countries[3]);
		System.out.println("Fifth Element: " + countries[4]);

	}

}

Output:
First Element: USA
Second Element: AUSTRALIA
Third Element: NEWZEALAND
Fourth Element: INDIA
Fifth Element: JAPAN

Sorting Arrays

Sorting the data into specific order such as ascending or descending order is one of the critical parts of programming.

Arrays class provides method Arrays.sort() which can be used to sort the arrays, let’s see some sorting examples.

Sorting Arrays in Ascending Order

Below is the java program which sorts Integer array elements in ascending order.

import java.util.Arrays;
import java.util.Collections;

public class SortArray {

	public static void main(String[] args) {
		
		Integer[] scores = {60,50,40,80,90};
		Arrays.sort(scores);
		System.out.println("Sorting in Ascending Order: "+Arrays.toString(scores));
	}

}

Output:
Sorting in Ascending Order: [40, 50, 60, 80, 90]

Sorting Arrays in Descending Order

Below is the java program which sorts Integer array elements in descending order.

import java.util.Arrays;
import java.util.Collections;

public class SortArray {

	public static void main(String[] args) {
		
		Integer[] scores = {60,50,40,80,90};
		Arrays.sort(scores,Collections.reverseOrder());
	    System.out.println("Sorting in Descending Order: "+Arrays.toString(scores));
	}

}

Output:
Sorting in Descending Order: [90, 80, 60, 50, 40]

Looping Array Elements

We can iterate through each element of the array using loops in Java.

Here is the example of looping array elements using for loop.

public class ForLoopArray {

	public static void main(String[] args) {

		int[] count = { 6, 8, 10 };

		for (int i = 0; i < count.length; i++) {
			System.out.println(count[i]);
		}

	}

}

Output:
6
8
10

We can also loop through array elements using for each loop, here is the example

public class ForEachArray {

	public static void main(String[] args) {

		int[] count = { 6, 8, 10 };

		for (int i : count) {
			System.out.println(i);
		}

	}

}

Output:
6
8
10

Searching Arrays

In order to determine whether an array contains a value that matches a specific key-value, a search will be performed which is nothing but locating a key value in an array.

we have search techniques like a linear search and binary search for searching and matching array values.

Linear Search of an Array

we use linear search to search a specific element from numerous array elements.

Typically linear search is the best fit for small arrays or for unsorted arrays.

The linear search algorithm works in the following way.

  1. Traversing an array.
  2. Match the specific element with respective array element.
  3. Match the specific element with respective array element.
  4. If a matching element is found, then it will return the index position of the array element.
  5. if a matching element is not found, then it will return -1.

Here is the example program for Linear Search.

public class LinearSearch {

	public static void main(String[] args) {
		
		 int[] num= {60,50,40,80,90};  
		 int searchKey = 80;
		for(int i=0;i < num.length;i++){    
	            if(num[i] == searchKey){    
	            	System.out.println("Array Index Position is: "+i);  
	            }    
	        }    
	}

}


Output:
Array Index Position is: 3

Binary Search of an Array

For searching through larger sorted arrays, binary search is apt and provides high-speed search results.

The binary search algorithm works in the following way.

  1. Eliminates half of the elements in the given array being searched after having each comparison.
  2. It identifies the middle array element and compares it with the key used to search.
  3. If a matching element is found, then it will return the index position of the array element
  4. if a matching element is not found and if the search key is less than the middle array element, the first half of the array will be searched; else, the second half of the array will be searched.
  5. The search continues until the search key is equal to the middle element of a subarray or till the subarray consists of one element that is not equal to the search key.

Here is the example program for Binary Search.

public class BinarySearch {

	public static void main(String[] args) {
		
		 int[] num= {10,20,30,40,50};  
		 int searchKey = 40;
		 int first = 0 ; 
		 int last=num.length-1;  
		 
		 int midArray = (first + last)/2 ; 
		   while( first <= last ){  
		      if ( num[midArray] < searchKey ){  
		        first = midArray + 1;     
		      }else if (  num[midArray] == searchKey ){  
		        System.out.println("Array Index Position is: " + midArray);  
		        break;  
		      }else{  
		         last = midArray - 1;  
		      }  
		      midArray = (first + last)/2;  
		   }  
		   if ( first > last ){  
		      System.out.println("Array Element is not Found");  
		   }  
		 }  
	}

Output:
Array Index Position is: 3

Dynamic Array in Java

we know that the array contains is a fixed-size entity, which means we have to specify the number of elements while array declaration.

so the challenge is if we need to insert an element but there is no more space available to accommodate the new element? Here comes the savior called Dynamic Array which expands the array size dynamically.

Java Dynamic Array grows automatically when there is no enough space to accommodate the insertion of the new element.

In Java, dynamic array is nothing but an ArrayList.

Dynamic Array Features

  • Add Array Element.
  • Delete Array Element.
  • Resizing an Array.

Advantages of Dynamics Array

  • Cache Friendly.
  • Dynamic Variable Size.
  • Quick Looping.

Disadvantages of Dynamics Array

  • Inserts and Deletes taking more time.
  • Slow Appends.

Pin It on Pinterest

Share This