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.

The key to solving array-based interview questions or any coding challenge is having a good knowledge of array data structure.

Declaring Creating and Initializing 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 (1D array) and Multi Dimensional Arrays(2D array or more 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.

A multi-dimensional array is also referred as ragged array or jagged array.

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 with the Array API

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 sorted array 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

we can also utilize Arrays.binarySearch() method to perform a binary search in an array. Here is the example

import java.util.Arrays;

public class BinarySearchArray {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] num = { 10, 20, 30, 40, 50 };
		int searchKey = 40;
		int resultPostion = Arrays.binarySearch(num, searchKey);
		System.out.println("Array Index Position is: " + resultPostion);
	}
}

Output:
Array Index Position is: 3

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.

The key to solving array-based interview questions or any coding challenge is having a good knowledge of array data structure.

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.

Array vs ArrayList

Here are the notable difference between an Array and ArrayList.

  • Array is having a fixed length, where as in Arraylist the length will be dynamic.
  • Array length cannot be changed once it created, where as in Arraylist the length can be changed.
  • Array can store both primitive types and Objects, where as Arraylist can only store Objects but not primitive types.
  • To access the elements in an ArrayList, we use the .get method, and to update elements in an ArrayList, we use the .set method. If we want to add an element, we can use the .add element.

Array of Objects

Array of Objects, the name itself mentions that it is meant for storing an array of objects.

Take a note that, the reference of the object will be stored not the Object itself.

Creating Array of Objects

Array of Objects is created using the Objects class and here is the syntax

Class_Name[ ] arrayReference;

For example, if you have a class Employee then we can create an array of Employee objects as below:

Employee[ ] employeeObjects;

Instantiate an Array of Objects

In order to instantiate the array of objects in java, here is the syntax.

Class_Name object[ ]= new Class_Name[ArrayLength];

For example, if you have a class Employee, and want to declare and instantiate an array of Employee objects then it can be implemented as:

Employee[ ] employeeObjects = new Employee[4];

Now let’s see an example program for an array of objects in java as below.


public class Employee {

	private int id;
	private String name;
	private String dept;

	Employee(int id, String name, String dept) {
		this.id = id;
		this.name = name;
		this.dept = dept;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", dept=" + dept + "]";
	}

}


public class ArrayObjects {

	public static void main(String[] args) {
		
		Employee[] employeeObjects = new Employee[3];
		employeeObjects[0] = new Employee(1, "Sam", "CSE");
		employeeObjects[1] = new Employee(2, "John", "ECE");
		employeeObjects[2] = new Employee(3, "Mike", "IT");

		for (Employee i : employeeObjects) {
			System.out.println("Array Data is : " + i);
		}
	}

}


Output:
Array Data is : Employee [id=1, name=Sam, dept=CSE]
Array Data is : Employee [id=2, name=John, dept=ECE]
Array Data is : Employee [id=3, name=Mike, dept=IT]

Concatenate Arrays

In order to concatenate arrays in java, we can achieve this in numerous ways.

Let’s see some sample implementation’s below for concatenating arrays.

Here is the example using ArrayUtils.addAll(T[], T...) method from Apache Commons Lang library.

import org.apache.commons.lang3.ArrayUtils;

public class ConcatenateArrays {

	public static void main(String[] args) {

		String[] first = { "a", "b", "c" };
		String[] second = { "d", "e", "f" };

		String[] result = ArrayUtils.addAll(first, second);

		System.out.println("Concatenate Results are : " + result.length);

		for (String x : result) {
			System.out.println("Array Element is : " + x);
		}
	}

}

Output:
Concatenate Results are : 6
Array Element is : a
Array Element is : b
Array Element is : c
Array Element is : d
Array Element is : e
Array Element is : f

Also using Java 8 Stream, we can concatenate arrays.

Here is the example program which uses Java Stream.

import java.util.Arrays;
import java.util.stream.Stream;

public class ConcatenateStream {

	public static void main(String[] args) {

		String[] first = { "a", "b", "c" };
		String[] second = { "d", "e", "f" };

		String[] result = Stream.concat(Arrays.stream(first), Arrays.stream(second)).toArray(String[]::new);

		System.out.println("Stream Results are : " + result.length);

		for (String x : result) {
			System.out.println("Array Element is : " + x);
		}
	}

}

Output:
Stream Results are : 6
Array Element is : a
Array Element is : b
Array Element is : c
Array Element is : d
Array Element is : e
Array Element is : f

We can use flatMap which is another Java 8 method that can be used to concatenate arrays.

Here is the example which uses Java flatMap.

import java.util.stream.Stream;

public class ConcatenateFlatMap {

	public static void main(String[] args) {

		String[] first = { "a", "b", "c" };
		String[] second = { "d", "e", "f" };

		String[] result = Stream.of(first, second).flatMap(Stream::of).toArray(String[]::new);

		System.out.println("FlatMap Results are : " + result.length);

		for (String x : result) {
			System.out.println("Array Element is : " + x);
		}
	}

}

Output:
FlatMap Results are : 6
Array Element is : a
Array Element is : b
Array Element is : c
Array Element is : d
Array Element is : e
Array Element is : f

Using Generics, we can achieve concatenation of arrays by leveraging reflection concept.

As you might know, reflection allows methods to access array and array component types, creating new arrays, retrieving, and setting array component values.

Here is the example which uses Generics implementation.

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.stream.Stream;

public class ConcatenateGenerics {

	public static  void main(String[] args) {

		String[] first = { "a", "b", "c" };
		String[] second = { "d", "e", "f" };

		T[] result = Stream.concat(Arrays.stream(first), Arrays.stream(second))
				.toArray(size -> (T[]) Array.newInstance(first.getClass().getComponentType(), size));

		System.out.println("Generic Results are : " + result.length);

		for (T x : result) {
			System.out.println("Array Element is : " + x);
		}
	}

}


Output:
Generic Results are : 6
Array Element is : a
Array Element is : b
Array Element is : c
Array Element is : d
Array Element is : e
Array Element is : f

Pin It on Pinterest

Share This