Java Array Interview Questions and Answers
Java Array Interview Questions and Answers
Q1 What is an Array?
Array is a collection of similar data types. It can not have different data type. It can hold both primitive types (int, float, double)
and object references.
It is fixed in length i.e static in nature.
Arrays are created on the heap memory not on the stack.
Accessing an invalid index of an Array will cause exception.
This exception is thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.
In other words, if you want to store the integer Object in an Array of String you will get ArrayStoreException.
ArrayOutOfBoundsException is thrown when an attempt is made to access the Array with illegal index. For example, illegal
index means if the index is either negative or greater than or equal to the size of the Array.
b. The Array is static data structure. It is of fixed size. We can not increase or decrease the size of the Array after creation.
Output :
23 17 20 29 30
import java.util.*;
public class JavaHungry {
Output :
17 20 23 29 30
Q17 Write a program to check whether two given Arrays are equal, given both contains same data type and same length ?
To check whether two given arrays are equal or not , we can use Arrays.equals() method. Check the program below :
import java.util.*;
public class JavaHungry {
System.out.println(Arrays.equals(arr1 , arr2));
System.out.println(Arrays.equals(arr1 , arr3));
}
}
Output :
false
true
Q23 How to find the missing number in a given Array from number 1 to 100 ?
This question is a popular interview question. I have shared the code with explanation here.
Q25 There are two arrays object one containing 100 elements and another containing 50 elements. Both are of same data
type. Can we assign one Array to another Array.
Yes, an Array of 100 elements can be assigned to an Array of 50 elements in java. The only criteria is that both arrays of same
data type. It is because at the time of assigning the values compiler looks for the data type of Array not the size of Array.
import java.util.*;
public class JavaHungry {
public static void main(String args[]) {
int[] arr1 = new int[50];
int[] arr2 = new int[100];
arr1 = arr2;
System.out.println(arr1.length);
}
}
Output :
100
Q26 What are the different ways to copy one Array from another Array?
There are four ways by which we can copy an Array.
a. By using for loop
b. By using clone() method
c. By using Arrays.copyOf() method
d. By using System.arraycopy() method
}
}
}
}
}
Output:
Duplicate in Array is : java
Duplicate in Array is : javahungry
HashSet does not allow duplicate elements. You can traverse the array and insert each element into the HashSet. Add elements
using add() method. If it returns true then continue to traverse the array. Otherwise if false then print out the duplicate value.
Q31 Is this a legal way to define arrays int[] arr = new int [4]{1, 2, 3, 4};
This is invalid way to initialize an Array in Java. You can not provide the size of the Array when you are declaring the elements in
it.
Q32 What is two dimensional Array in java?
An Array of an Array in java is called as two dimensional Array.
Q37 Given two arrays, find the intersection between them? (solution)
Intersection means common elements. We need to find common elements between two given arrays.
For example :
int[] arr1 = {1, 2, 3, 4, 5, 6};
int[] arr2 = {2, 3, 4, 7, 8};
Output : 2, 3, 4
You can find the code here.
Q38 Find the missing number in an Array between 1 to 100. Given only one number is missing. (solution)
This question is very popular among interviewers. It is one of the simplest question in Array topic.
This question is generally asked during telephonic interview or as a warm up question in face to face round of interviews.
One of the ways to solve this problem is to calculate sum of all numbers from 1 to 100 then subtract it from the sum of all the
numbers in given array. Difference would be the missing number.
Q41 Write a program to sum all the values of a given Array in java?
public class JavaHungry {
public static void main(String args[]) {
// Given Array
int[] inputArr = {10,43,27,98,75,59,191};
int sum = 0;
//Iterating through the Array
for(int num : inputArr) {
sum = sum + num;
}
System.out.println(sum);
}
}
Output :
503
Q43 How do you separate zeros and non-zeros in a given Array in java?
Logic to separate zeros and non-zeros is given below :
a. Initialize variable counter to 0.
b. Iterating inputArr from left to right. If inputArr[i] is not zero then assign inputArr[i] to inputArr[counter].
c. Increment the counter by 1.
d. Assign the remaining elements with 0 value.
import java.util.*;
public class JavaHungry {
public static void main(String args[]) {
// Given Array
int[] inputArr = {0,10,43,27,0,98,75,59,191,0};
int counter = 0;
//Iterating through the Array
for(int i=0;i < inputArr.length;i++) {
if(inputArr[i] != 0) {
inputArr[counter] = inputArr[i];
counter++;
}
}
while (counter < inputArr.length) {
inputArr[counter] = 0;
counter++;
}
System.out.println(Arrays.toString(inputArr));
}
}
Output:
[10, 43, 27, 98, 75, 59, 191, 0, 0, 0]
Q47 Write a program to find second largest element in a given Array in java?
The easiest way to solve this problem by using sorting. Sort the given Array and then iterate to the second last element.
import java.util.*;
public class LargestSmallest
{
public static void main(String[] args)
{
// Given Array
int inputArray[] = new int[] {10,43,27,98,75,59,191};
// Sort Array
Arrays.sort(inputArray);
// Iterate Array to Second last element
for(int i=0; i < inputArray.length; i++) {
// Print second last element
if(i == inputArray.length- 2)
System.out.println(inputArray[i]);
}
}
}
Output :
98
Q49 Write a program to find the first repeating number in an integer Array?
a. Logic is declare a variable minimum. Iterate through the Array in reverse order i.e from last element to first element. Add
elements to the HashSet one by one.
b. If repeated value occurs then store the index of the repeated value to the minimum variable.
import java.util.*;
public class FirstRepeating {
public static void main(String args[]) {
int[] arr = new int[]{1,2,3,4,5,7,4,9};
firstRepeating(arr);
}
public static void firstRepeating(int[] arr) {
int minimum = -1;
HashSet set = new HashSet();
for (int i = arr.length-1 ;i >=0 ;i--) {
if(set.contains(arr[i]))
minimum = i;
else
set.add(arr[i]);
}
if(minimum != -1){
System.out.println("first repeating element is : "+ arr[minimum]);
}
}
}
Output :
first repeating element is : 4
Q50 Write a program to find the first non-repeating number in an integer Array?
Compare one element with rest of the remaining elements. If value does not match then exit the iteration and print the value.
public class FirstNonRepeating {
public static void main(String args[]) {
int[] arr = new int[]{1,2,3,4,5,1,2,3,5,9};
System.out.println(firstNonRepeating(arr,arr.length));
}
public static int firstNonRepeating(int[] arr, int length) {
int j;
for (int i=0; i < length ;i++) {
for(j=0; j < length ;j++) {
if (arr[i]==arr[j] && i!=j) {
break;
}
}
if (j == length)
return arr[i];
}
return -1;
}
}
Output :
4
------------------------------------------------------------set 2-------------------------------------
1. What is an Array in Java?
An array is a collection of elements (or data) of the same type that are referenced by a common name. For example, we can
store a group of strings, a group of int values, or a group of float values in the array. But, we cannot store some int values or
some float values in the array.
4. Name the keyword that is used for allocating memory space to an array?
Ans: new keyword
9. How to create an integer array of size 3 * 2 and initialize with values from 1 to 9?
Ans: int[ ][ ] x = {{2, 3}, {3, 5}, {5, 9}};
11. What is the total size of an array chrs having 25 elements of char type?
Ans: 50 bytes
16. Can we modify the size (or length) of the array once set it?
Or, can we insert or delete elements after creating an array?
Ans: No. Once the size of an array is defined, we cannot modify it. We cannot add or delete elements after creation of an array.
In other words, an array cannot expand or shrink at runtime.
17. What will happen when the following lines of code are compiled and executed?
int i = -3;
int[ ] arr = new int[i];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
Ans: The code above will compile fine but at runtime, it will throw an exception named NegativeArraySizeException because i is
a negative number that cannot be used as an array index.
19. Will the above lines of code compile and execute successfully? If yes, what will be the output?
public class Test {
public static void main(String[] args)
{
int i = 4;
String[ ] arr = new String[i];
arr[0] = "A";
arr[1] = "B";
arr[2] = "C";
System.out.print(Arrays.toString(arr));
}
}
Ans: Yes, the code will be compiled successfully. The output is [A, B, C, null].
20. Which exception will be thrown at runtime when the below code will be compiled?
public class Test {
public static void main(String[] args)
{
Object[ ] arr = new String[3];
arr[0] = "A";
arr[1] = "B";
arr[2] = 20;
System.out.print(Arrays.toString(arr));
}
}
Ans: The code will compile fine but at runtime, we will get ArrayStoreException (runtime exception). This exception generally
occurs when we attempt to store non-compatible elements in an array object.
The type of the elements must be compatible with the type of array object. For example, we can store only string elements in
an array of type String. If we will attempt to insert integer elements in an array of String, an ArrayStoreException will be thrown
at runtime.
21. For the below code, what will be the total size taken by the whole array in the memory?
double[ ] num = new double[10];
Ans: Each element in the num array is a variable of double type that needs 8 bytes in the memory. So, the whole array will take
space 80 bytes in the memory, plus 8 bytes for the num variable to store the reference of array in the memory.
22. What is the difference between int[ ] arr and int arr[ ]?
Ans: There is no difference between int[ ] arr and int arr[ ]. Both are the legal ways to declare an array in java. int[ ] arr is a
standard declaration.
25. Is there any error in the below code? If not, what is the output of the following program?
import java.util.Arrays;
public class Test {
public static void main(String[] args)
{
String[ ] str = new String[5];
str[0] = "A";
str[1] = "20";
str[3] = "B";
str[4] = "C";
System.out.println(Arrays.toString(str));
}
}
Ans: No, there is no error in the above lines of code. The output will be [A, 20, null, B, C].
26. What is the difference between length() method and length in java?
Ans: The length() method is provided by String class that is used to return the number of characters in the string. For example:
String str = "Hello world";
System.out.println(str.length());
str.length(); will return 11 characters including space.
Whereas, length is an instance variable in arrays that will return the number of values or objects in array. For example:
String[ ] names = {"John", "Herry", "Deepak", "Ivaan", "Ricky"};
System.out.println(names.length);
names.length; will return 5 since the number of values in names array is 5.
27. What is the important difference between an Array and ArrayList in Java?
Ans: There are the following important differences between Arraya and ArrayList in Java. They are as follows:
Array:
Array is static in size. It has a fixed size.
We cannot change the size (or length) of the array after creating it.
An array can contain both primitive data types as well as reference types.
Array in java does not support generics.
Elements of an array can be iterated using for loop.
An Array can be multi-dimensional.
ArrayList:
ArrayList is dynamic in size.
The size of the ArrayList grows or shrinks automatically as we insert or remove elements.
ArrayList cannot contain primitive data types. It contains only objects. That is, we can store only reference types in ArrayList.
ArrayList in java supports generics.
In an ArrayList, we can use an Iterator object to traverse elements.
Arraylist is always of a single dimension.
28. Which one is the preferred collection for storing objects between an Array and ArrayList?
Ans: ArrayList is backed up by array internally. There are several usability advantages of using an ArrayList over an array in Java.
They are:
a) An array has a fixed length at the time of creation. Once it is created we cannot modify its length.
ArrayList is dynamic in size. Once it reaches a threshold, it automatically allots a new array and copies the contents of old array
to the new array.
b) Also, ArrayList supports Generics. But Array does not support Generics.
The array should be used in the place of an ArrayList if
We know the size of an array in advance and do not need re-sizing the collection.
We need to store the same type of elements.
37. Will the below code compile fine? If yes, what will be the output of the following program?
public class Test {
public static void main(String[] args)
{
int[ ] arr;
arr = new int[1];
arr = new int[2];
arr[0] = 20;
arr[1] = 30;
arr[2] = 40;
}
}
Ans: Yes, the code will compile fine but at runtime, we will get ArrayIndexOutOfBoundsException because once an array is
created, its size cannot be resized.
38. Is there any error in the below code? If not, what will be the output of the following program?
public class Test {
public static void main(String[] args)
{
int[ ] arr = new int[3];
int[ ] arr2 = new int[5];
arr2 = arr;
System.out.println(arr.length);
System.out.println(arr2.length);
}
}
Ans: Output: 3 3
42. Which new methods were introduced in Java 8 for the processing of Arrays on multi-core machines?
Ans: Java 8 has enhanced the Arrays class by introducing some new methods that can run efficiently on multi-core machines.
These methods start with keyword parallel.
For example, Arrays.parallelSetAll(), Arrays.parallelSort(), etc. These methods process Arrays in parallel to make Java code very
fast on a multi-core machine.
43. Suppose there are two array objects of int type. one has 20 elements and another one has 10 elements. Is it possible to
assign an array of 20 elements to an array of 10 elements?
Ans: Yes, it is possible to assign an array of 20 elements to an array of 10 elements provided they should be of the same type.
Java compiler checks only the type of the array, not the size while assigning. The sample code is as follows:
int[ ] x = new int[10];
int[ ] y = new int[20];
x = y; // Here, array references x and y both are pointing to the same array contents (i.e. array of 20 elements).
44. Identify and fix errors in the below code. What will be output after fixing them?
import java.util.Arrays;
public class Test {
public static void main(String[] args)
{
int num[ ] = new int[6]{1, 2, 3, 4, 5, 6};
System.out.println(Arrays.toString(num));
}
}
Ans: We need not define the size of the array when we are storing the array contents. After removing the size of array, the
output is [1, 2, 3, 4, 5, 6]
49. Which method of the Arrays class can be used to search/find a particular element in an array?
Ans: The Arrays.binarySearch() method can be used to search/find a particular element in an array. This method uses the binary
search algorithm.
The array should be in natural ordering (either in ascending or descending order) before calling it. This is the simplest and most
efficient approach to find an element in a sorted array.
50. What is the difference between linear search and binary search in java?
Ans: Binary search is much faster than linear search for a large array. Binary search algorithm is mostly used for large size array
whereas, linear search is used for very small size array.
52. What are the simple approaches to find duplicate elements in an array?
Ans: There are mainly three simple approaches to find duplicate elements from an array.
a) Brute Force Method: In this approach, each element of an array is compared with elements of another array. If any two
elements are found equivalent, we consider them as duplicates. The time complexity of this approach is O(n^2).
b) Using HashSet: In this approach, we use the HashSet class to find the duplicate elements in an array. To find the duplicate
elements, first iterate over the array elements and then add them into HashSet by calling add() method of the HashSet class.
If the method returns false it means that the element is already present in the Set. It takes O(n) time to find the duplicate
elements.
c) Using HashMap: We can also use HashMap to find duplicate elements in an array. HashMap uses key-value pair to store an
element.
To find the duplicate array element, we store elements of the array as keys and their occurrence as values. If the value of any
key is greater than 1, the key is considered a duplicate element. Its time and space complexity is O(n).
55. Identify and fix the error in the following lines of code.
int x;
int[ ] num = {2, 4, 6, x, 10};
Ans: There is an error in the first line of code because the variable x is not initialized.