Array concept is the must know concept for Java freshers. If you are attending a technical interview for Java developer position, it is sure that you will get one or two questions on arrays. In this post, I have collected some likely Java array interview questions and have tried to answer them. I hope it will be useful in your Java interview preparation.
Java Array Interview Questions And Answers :
1) What is an array?
Array is a collection of same type of objects or values where each value or object is identified by an index. You can make an array of int’s, double’s, boolean’s or any other types but all the values of an array must be of same type.
2) What are the different ways to create arrays in Java?
a) Creating an array without elements :
int[] a = new int[10]
OR
int a[] = new int[10]
b) Creating an array with elements :
int[] a = new int[] {1, 2, 3, 4 ,5}
OR
int a[] = new int[] {1, 2, 3, 4 ,5}
3) What is ArrayStoreException in Java? When you will get this exception?
ArrayStoreException is a run time exception which occurs when you try to store non-compatible element in an array object. The type of the elements must be compatible with the type of an array object. For example, you can store only string elements in an array of strings. if you try to insert integer element in an array of strings, you will get ArrayStoreException at run time.
public class JavaArrayExample
{
public static void main(String[] args)
{
Object[] stringArray = new String[5]; //No compile time error : String[] is auto-upcasted to Object[]
stringArray[1] = "JAVA";
stringArray[2] = 100; //No compile time error, but this statement will throw java.lang.ArrayStoreException at run time
//because we are inserting integer element into an array of strings
}
}
4) Can you pass the negative number as an array size?
No. You can’t pass the negative integer as an array size. If you pass, there will be no compile time error but you will get NegativeArraySizeException at run time.
public class JavaArrayExample
{
public static void main(String[] args)
{
int[] array = new int[-5]; //No compile time error
//but you will get java.lang.NegativeArraySizeException at run time
}
}
5) Can you change the size of an array once you define it?
OR
Can you insert or delete the elements after creating an array?
No. You can’t change the size of an array once you define it. You can’t insert or delete the elements after creating an array. Only you can do is change the value of the elements.
6) What is an anonymous array? Give example?
Anonymous array is an array without reference. For example,
public class JavaArrayExample
{
public static void main(String[] args)
{
//Creating anonymous arrays
System.out.println(new int[]{1, 2, 3, 4, 5}.length); //Output : 5
System.out.println(new int[]{21, 14, 65, 24, 21}[1]); //Output : 14
}
}
7) What is the difference between int[] a and int a[] ?
Both are the legal ways to declare the arrays in Java.
8) There are two array objects of int type. One is containing 100 elements and another one is containing 10 elements. Can you assign an array of 100 elements to an array of 10 elements?
Yes, you can assign an array of 100 elements to an array of 10 elements provided they should be of same type. While assigning, compiler checks only the type of an array not the size.
public class JavaArrayExample
{
public static void main(String[] args)
{
int[] a = new int[10];
int[] b = new int[100];
a = b; //Compiler checks only type, not the size
}
}
9) “int a[] = new int[3] {1, 2, 3}” – is it a legal way of defining the arrays in Java?
No. You should not mention the size of an array when you are providing the array contents.
10) What are the differences between Array and ArrayList in Java?
| Array | ArrayList |
| Arrays are static in nature. Arrays are fixed length data structures. You can’t change their size once they are created. | ArrayList is dynamic in nature. Its size is automatically increased if you add elements beyond its capacity. |
| Arrays can hold both primitives as well as objects. | ArrayList can hold only objects. |
| Arrays can be iterated only through for loop or for-each loop. | ArrayList provides iterators to iterate through their elements. |
| The size of an array is checked using length attribute. | The size of an ArrayList can be checked using size() method. |
| Array gives constant time performance for both add and get operations. | ArrayList also gives constant time performance for both add and get operations provided adding an element doesn’t trigger resize. |
| Arrays don’t support generics. | ArrayList supports generics. |
| Arrays are not type safe. | ArrayList are type safe. |
| Arrays can be multi-dimensional. | ArrayList can’t be multi-dimensional. |
| Elements are added using assignment operator. | Elements are added using add() method. |
11) Where the arrays are stored in the memory?
Arrays are nothing but the objects in Java. Hence, they are stored in heap memory like normal objects.
12) What are the different ways of copying an array into another array?
There are four ways available in Java to copy an array.
1) Using for loop
2) Using Arrays.copyOf() method
3) Using System.arraycopy() method
4) Using clone() method
Click here to see these methods in detail.
13) What are jagged arrays in Java? Give example?
Jagged arrays in Java are the arrays containing arrays of different length. Jagged arrays are also multidimensional arrays. They are also called as ragged arrays.
Click here to see the jagged arrays in detail.
14) How do you check the equality of two arrays in Java?
You can use Arrays.equals() method to compare one dimensional arrays and to compare multidimensional arrays, use Arrays.deepEquals() method.
Click here to see more info on comparing two arrays in Java.
15) What is ArrayIndexOutOfBoundsException in Java? When it occurs?
ArrayIndexOutOfBoundsException is a run time exception which occurs when your program tries to access invalid index of an array i.e negative index or index higher than the size of an array.
16) How do you sort the array elements?
You can sort the array elements using Arrays.sort() method. This method internally uses quick sort algorithm to sort the array elements.
import java.util.Arrays;
public class JavaArrayExample
{
public static void main(String[] args)
{
int[] a = new int[]{45, 12, 78, 34, 89, 21};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
//Output : [12, 21, 34, 45, 78, 89]
}
}
17) How do you find the intersection of two arrays in Java?
Below is the code to find the common elements or intersection of two arrays in Java.
class CommonElements
{
public static void main(String[] args)
{
String[] s1 = {"ONE", "TWO", "THREE", "FOUR", "FIVE", "FOUR"};
String[] s2 = {"THREE", "FOUR", "FIVE", "SIX", "SEVEN", "FOUR"};
HashSet<String> set = new HashSet<String>();
for (int i = 0; i < s1.length; i++)
{
for (int j = 0; j < s2.length; j++)
{
if(s1[i].equals(s2[j]))
{
set.add(s1[i]);
}
}
}
System.out.println(set); //OUTPUT : [THREE, FOUR, FIVE]
}
}
Click here to see more about intersection of two arrays in Java.
18) What are the different ways of declaring multidimensional arrays in Java?
The following code snippet shows different ways of declaring 2D, 3D and 4D arrays.
//2D Arrays
int[][] twoDArray1;
int twoDArray2[][];
int[] twoDArray3[];
//3D Arrays
int[][][] threeDArray1;
int threeDArray2[][][];
int[] threeDArray3[][];
int[][] threeDArray4[];
//4D Arrays
int[][][][] fourDArray1;
int fourDArray2[][][][];
int[] fourDArray3[][][];
int[][] fourDArray4[][];
int[][][] fourDArray5[];
19) While creating the multidimensional arrays, can you specify an array dimension after an empty dimension?
No, you can’t specify an array dimension after an empty dimension while creating multidimensional arrays. It gives compile time error.
int[][][] a = new int[][5][]; //Compile time error
int[][][] b = new int[5][][5]; //Compile time error
int[][][] c = new int[][5][5]; //Compile time error
20) How do you search an array for a specific element?
You can search an array to check whether it contains the given element or not using Arrays.binarySearch() method. This method internally uses binary search algorithm to search for an element in an array.
21) What value does array elements get, if they are not initialized?
They get default values.
22) What are the different ways to iterate over an array in java?
1) Using normal for loop
public class JavaArrayExample
{
public static void main(String[] args)
{
int[] a = new int[]{45, 12, 78, 34, 89, 21};
//Iterating over an array using normal for loop
for (int i = 0; i < a.length; i++)
{
System.out.println(a[i]);
}
}
}
2) Using for-each loop
public class JavaArrayExample
{
public static void main(String[] args)
{
int[] a = new int[]{45, 12, 78, 34, 89, 21};
//Iterating over an array using extended for loop
for (int i : a)
{
System.out.println(i);
}
}
}
23) How do you convert a List or Set to an array?
Using toArray() method.
24) What is the time complexity of different operations on arrays?
| Operations | Time Complexity (Worst Case Scenario) |
| Modify (You can’t insert or delete elements once an array is created. What you can do is just change value of an existing element) | O(1) |
| Search | O(n) |
| Retrieval | O(1) |
25) What are the main drawbacks of the arrays in Java?
The main drawback of the arrays is that arrays are of fixed size. You can’t change the size of the array once you create it. Therefore, you must know how many elements you want in an array before creating it. You can’t insert or delete the elements once you create an array. Only you can do is change the value of the elements.
26) How do you find duplicate elements in an array?
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
public class DuplicatesInArray
{
//Method 1 : Brute Force Method
private static void findDuplicatesUsingBruteForce(int[] inputArray)
{
for (int i = 0; i < inputArray.length; i++)
{
for (int j = i+1; j < inputArray.length; j++)
{
if(inputArray[i] == inputArray[j])
{
System.out.println("Duplicate Element : "+inputArray[i]);
}
}
}
}
//Method 2 : Sorting Method
private static void findDuplicatesUsingSorting(int[] inputArray)
{
Arrays.sort(inputArray);
for (int i = 0; i < inputArray.length-1; i++)
{
if(inputArray[i] == inputArray[i+1])
{
System.out.println("Duplicate Element : " + inputArray[i]);
}
}
}
//Method 3 : Using HashSet
private static void findDuplicatesUsingHashSet(int[] inputArray)
{
HashSet<Integer> set = new HashSet<Integer>();
for (int element : inputArray)
{
if( ! set.add(element))
{
System.out.println("Duplicate Element : "+element);
}
}
}
//Method 4 : Using HashMap
private static void findDuplicatesUsingHashMap(int[] inputArray)
{
HashMap<Integer, Integer> map = new HashMap<>();
for (int element : inputArray)
{
if(map.get(element) == null)
{
map.put(element, 1);
}
else
{
map.put(element, map.get(element)+1);
}
}
Set<Entry<Integer, Integer>> entrySet = map.entrySet();
for (Entry<Integer, Integer> entry : entrySet)
{
if(entry.getValue() > 1)
{
System.out.println("Duplicate Element : "+entry.getKey()+" - found "+entry.getValue()+" times.");
}
}
}
//Method 5 : Using Java 8 Streams
private static void findDuplicatesUsingJava8(int[] inputArray)
{
Set<Integer> uniqueElements = new HashSet<>();
Set<Integer> duplicateElements = Arrays.stream(inputArray)
.filter(i -> !uniqueElements.add(i))
.boxed()
.collect(Collectors.toSet());
System.out.println(duplicateElements);
}
public static void main(String[] args)
{
int[] inputArray = new int[] {111, 333, 555, 777, 333, 444, 555};
System.out.println("======Duplicates Using Brute Force======");
findDuplicatesUsingBruteForce(inputArray);
System.out.println("======Duplicates Using Sorting======");
findDuplicatesUsingSorting(inputArray);
System.out.println("======Duplicates Using HashSet======");
findDuplicatesUsingHashSet(inputArray);
System.out.println("======Duplicates Using HashMap======");
findDuplicatesUsingHashMap(inputArray);
System.out.println("======Duplicates Using Java 8 Streams======");
findDuplicatesUsingJava8(inputArray);
}
}
27) How do you find a missing number in an array of integers if it contains elements from 1 to n where n is the number of elements?
public class MissingNumberInArray
{
//Method to calculate sum of 'n' numbers
static int sumOfNnumbers(int n)
{
int sum = (n * (n+1))/ 2;
return sum;
}
//Method to calculate sum of all elements of array
static int sumOfElements(int[] array)
{
int sum = 0;
for (int i = 0; i < array.length; i++)
{
sum = sum + array[i];
}
return sum;
}
public static void main(String[] args)
{
int n = 8;
int[] a = {1, 4, 5, 3, 7, 8, 6};
//Step 1
int sumOfNnumbers = sumOfNnumbers(n);
//Step 2
int sumOfElements = sumOfElements(a);
//Step 3
int missingNumber = sumOfNnumbers - sumOfElements;
System.out.println("Missing Number is = "+missingNumber);
}
}
28) How do you remove duplicate elements from an array?
import java.util.Arrays;
public class RemoveDuplicatesJavaExample
{
static void removeDuplicates(int[] arrayWithDuplicates)
{
System.out.println("Array With Duplicates : ");
for (int i = 0; i < arrayWithDuplicates.length; i++)
{
System.out.print(arrayWithDuplicates[i]+"\t");
}
//Assuming all elements in input array are unique
int noOfUniqueElements = arrayWithDuplicates.length;
//Comparing each element with all other elements
for (int i = 0; i < noOfUniqueElements; i++)
{
for (int j = i+1; j < noOfUniqueElements; j++)
{
//If any two elements are found equal
if(arrayWithDuplicates[i] == arrayWithDuplicates[j])
{
//Replace duplicate element with last unique element
arrayWithDuplicates[j] = arrayWithDuplicates[noOfUniqueElements-1];
//Decrementing noOfUniqueElements
noOfUniqueElements--;
//Decrementing j
j--;
}
}
}
//Copying only unique elements of arrayWithDuplicates into arrayWithoutDuplicates
int[] arrayWithoutDuplicates = Arrays.copyOf(arrayWithDuplicates, noOfUniqueElements);
//Printing arrayWithoutDuplicates
System.out.println();
System.out.println("Array Without Duplicates : ");
for (int i = 0; i < arrayWithoutDuplicates.length; i++)
{
System.out.print(arrayWithoutDuplicates[i]+"\t");
}
System.out.println();
System.out.println("==============================");
}
public static void main(String[] args)
{
removeDuplicates(new int[] {4, 3, 2, 4, 9, 2});
removeDuplicates(new int[] {1, 2, 1, 2, 1, 2});
removeDuplicates(new int[] {15, 21, 11, 21, 51, 21, 11});
removeDuplicates(new int[] {7, 3, 21, 7, 34, 18, 3, 21});
}
}
29)How do you find the most frequent element in an array?
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
public class MostFrequentElementProgram
{
static void getMostFrequentElement(int inputArray[])
{
//Creating HashMap object with elements as keys and their occurrences as values
HashMap<Integer, Integer> elementCountMap = new HashMap<Integer, Integer>();
//Inserting all the elements of inputArray into elementCountMap
for (int i : inputArray)
{
if (elementCountMap.containsKey(i))
{
//If an element is present, incrementing its count by 1
elementCountMap.put(i, elementCountMap.get(i)+1);
}
else
{
//If an element is not present, put that element with 1 as its value
elementCountMap.put(i, 1);
}
}
int element = 0;
int frequency = 1;
//Iterating through elementCountMap to get the most frequent element and its frequency
Set<Entry<Integer, Integer>> entrySet = elementCountMap.entrySet();
for (Entry<Integer, Integer> entry : entrySet)
{
if(entry.getValue() > frequency)
{
element = entry.getKey();
frequency = entry.getValue();
}
}
//Printing the most frequent element in array and its frequency
if(frequency > 1)
{
System.out.println("Input Array : "+Arrays.toString(inputArray));
System.out.println("The most frequent element : "+element);
System.out.println("Its frequency : "+frequency);
System.out.println("========================");
}
else
{
System.out.println("Input Array : "+Arrays.toString(inputArray));
System.out.println("No frequent element. All elements are unique.");
System.out.println("=========================");
}
}
public static void main(String[] args)
{
getMostFrequentElement(new int[]{4, 5, 8, 7, 4, 7, 6,7});
getMostFrequentElement(new int[]{1, 2, 7, 5, 3, 6});
}
}
30) How do you merge two unsorted arrays into single sorted array?
import java.util.Arrays;
public class MergeArrayProgram
{
private static int[] mergeArray(int[] arrayA, int[] arrayB)
{
int[] mergedArray = new int[arrayA.length + arrayB.length];
int i=0, j=0, k=0;
while (i < arrayA.length)
{
mergedArray[k] = arrayA[i];
i++;
k++;
}
while (j < arrayB.length)
{
mergedArray[k] = arrayB[j];
j++;
k++;
}
Arrays.sort(mergedArray);
return mergedArray;
}
public static void main(String[] args)
{
int[] arrayA = new int[] {12, -7, 18, 9, 37, -1, 21};
int[] arrayB = new int[] {27, 8, 71, -9, 18};
int[] mergedArray = mergeArray(arrayA, arrayB);
System.out.println("Array A : "+Arrays.toString(arrayA));
System.out.println("Array B : "+Arrays.toString(arrayB));
System.out.println("Merged Array : "+Arrays.toString(mergedArray));
}
}
31) How do you merge two sorted or unsorted arrays into single sorted array without duplicates?
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class MergeTwoArraysAndRemoveDuplicatesProgram
{
private static int[] mergeArraysAndRemoveDuplicates(int[] arrayA, int[] arrayB)
{
//Step 1 : Merging of two arrays
//Defining mergedArray with combined size of arrayA and arrayB
int[] mergedArray = new int[arrayA.length + arrayB.length];
//Initializing pointers of arrayA, arrayB and mergedArray with 0
int i=0, j=0, k=0;
//Inserting all elements of arrayA into mergedArray
while (i < arrayA.length)
{
mergedArray[k] = arrayA[i];
k++;
i++;
}
//Inserting all elements of arrayB into mergedArray
while (j < arrayB.length)
{
mergedArray[k] = arrayB[j];
k++;
j++;
}
//Step 2 : Removing duplicates from merged array
//Defining one HashSet object called setWithNoDuplicates
//Remember, HashSet allows only unique elements
Set<Integer> setWithNoDuplicates = new HashSet<>();
//Adding all elements of mergedArray into setWithNoDuplicates
for (int m = 0; m < mergedArray.length; m++)
{
setWithNoDuplicates.add(mergedArray[m]);
}
//Now, setWithNoDuplicates will have only unique elements of mergedArray
//So, now iterate setWithNoDuplicates and
//add its elements into new array called mergedArrayWithNoDuplicates
Iterator<Integer> it = setWithNoDuplicates.iterator();
int[] mergedArrayWithNoDuplicates = new int[setWithNoDuplicates.size()];
int n = 0;
//Adding all elements of setWithNoDuplicates into mergedArrayWithNoDuplicates
while (it.hasNext())
{
mergedArrayWithNoDuplicates[n] = it.next();
n++;
}
//Step 3 : Sorting merged array after removing duplicates
Arrays.sort(mergedArrayWithNoDuplicates);
return mergedArrayWithNoDuplicates;
}
public static void main(String[] args)
{
int[] arrayA = new int[] {7, -5, 3, 8, -4, 11, -19, 21};
int[] arrayB = new int[] {6, 13, -7, 0, 11, -4, 3, -5};
int[] mergedArray = mergeArraysAndRemoveDuplicates(arrayA, arrayB);
System.out.println("Array A : "+Arrays.toString(arrayA));
System.out.println("Array B : "+Arrays.toString(arrayB));
System.out.println("Sorted Merged Array With No Duplicates : ");
System.out.println(Arrays.toString(mergedArray));
}
}
32) How do you find smallest and second smallest element in an integer array?
import java.util.Arrays;
public class SmallestSecondSmallestElementInArray
{
private static void getSmallestAndSecondSmallestElement(int[] inputArray)
{
int smallest = inputArray[0];
int secondSmallest = inputArray[0];
for (int i = 0; i < inputArray.length; i++)
{
if (inputArray[i] < smallest)
{
secondSmallest = smallest;
smallest = inputArray[i];
}
else if (inputArray[i] > smallest && inputArray[i] < secondSmallest)
{
secondSmallest = inputArray[i];
}
}
System.out.println("Input Array : "+Arrays.toString(inputArray));
System.out.println("Smallest Element : "+smallest);
System.out.println("Second Smallest Element : "+secondSmallest);
}
public static void main(String[] args)
{
getSmallestAndSecondSmallestElement(new int[] {17, 11, 23, 64, 41, 88, 35});
System.out.println("===============================");
getSmallestAndSecondSmallestElement(new int[] {-9, 3, 36, -25, -9, 71, 0});
System.out.println("===============================");
getSmallestAndSecondSmallestElement(new int[] {21, 21, -18, -4, -11, 85, 7});
}
}
Also Read :

plz send me this type of questions to my mail.
Explained very nice. Helpful tutorial..
We can not change the array size once it is defined. But how the array size is decreasing/increasing by assigning through another array of same type.
Can anyone explain about how it happening internally?
Hi Rashmi,
It is not updating the existing array but the reference will start pointing to the other array in the memory that is how it looks like its size got increased.
You can check it using below code:
String[] names1 = new String[3];
System.out.println(“Initial HashCode of 1st Array:”+names1.hashCode());
String[] names2 = new String[10];
System.out.println(“Initial HashCode of 2nd Array:”+names2.hashCode());
names1 = names2;
System.out.println(“Final HashCode of 1st Array:”+names1.hashCode());
Output:
Initial HashCode of 1st Array:305808283
Initial HashCode of 2nd Array:2111991224
Final HashCode of 1st Array:2111991224
@Rashmi
becoz you are assigning the reference of array object it is also called as call by value
question no. 1. – 2nd half is wrong i.e For example, you can store only string elements in an array of strings. if you try to insert integer element in an array of strings, you will get ArrayStoreException at run time.c
It will give compile time error. i.e Type mismatch: cannot convert from int
to String
you are wrong bro bcoz its run time error
what is compile time error,run time error,store exception error?
Answer 19:
import java.util.HashMap;
import java.util.Map;
//19) How do you find duplicate elements in an array?
//https://javaconceptoftheday.com/java-array-interview-questions-and-answers/
public class FindDuplicatesInArray {
public static void main(String[] args) {
int[] a = { 2, 2, 2, 34, 3, 54, 56, 6, 6, 6, 5, 3, 34, 23, 2, 2, 5 };
Map map = dups(a);
for(Integer i : map.keySet()) {
if(map.get(i)>1) {
System.out.println(i + ” “);
}
}
}
static Map dups(int[] a) {
Map map = new HashMap();
for (int i : a) {
map.put(i, map.getOrDefault(i, 0)+1);
}
return map;
}
}
Answer 21:
import java.util.Arrays;
//21) How do you find second largest element in an array of integers?
//https://javaconceptoftheday.com/java-array-interview-questions-and-answers/
public class SecondLargest {
public static void main(String[] args) {
int [] a = {3333,44,55,676,33,22,55};
System.out.println(“Second largest: ” + sLargest(a));
}
static int sLargest(int[] a) {
int sl= -10000000;
int[] b = a.clone();
Arrays.sort(b);
int largest = largest(b);
for(int i: a) {
if(i == largest) continue;
if(i>sl) sl=i;
}
return sl;
}
static int largest(int[] b ) {
int l = -100000000;
for(int i : b) {
if(i>l) l = i;
}
return l;
}
}
nice one