Arrays are the most basic and the most frequently asked data structure in the technical and coding interviews. The concept of arrays is present in almost every programming question so the basic knowledge of it is a must. They are also used to implement many other data structures, such as lists, heaps, hash tables, deques, queues, stacks, strings.
Let’s look into some of the important array based interview questions along with some coding questions:
1. What are default values for different data types in array data structure?
Any new Array is always initialized with a default value as follows
- For byte, short, int, long - default value is zero (0).
- For object - default value is null.
- For float, double - default value is 0.0.
- For Boolean - default value is false.
2. Is it ok to declare array size as a negative number?
No. We cannot declare the negative integer as an array size. However, there will be no compile-time error. But, we will get a NegativeArraySizeException at run time.
3. Is it possible to use Generics with arrays?
No, we cannot use Generic with an array.
4. Write an algorithm to find a pair with the given sum in a linear time.
This can be done using the concept of hashing. Firstly, insert all the elements of the array in a map. Next step is to check if the difference (array[i], sum - array[i]) is already present in the map or not, if it's there, then print the pair and return.
function findPair(int arr[], int n, int sum)
{
Declare an empty map
Run a loop for each element in map
{
Check if pair `(arr[i], sum - arr[i])` exists
If the difference is seen before, print the pair
{
Print pair found
return;
}
Store index of the current element in the map
}
Print Pair not found
}
5. Where does an array store in the memory?
Array creation is done inside the heap space of JVM memory. Arrays are an object in Java, so if it's created locally inside any block or method, an object is always allocated memory from the heap.
6. What are dynamic arrays?
A dynamic array is an array with automatic resizing. One limitation of arrays is that they're fixed size, meaning you need to specify the number of elements your array will hold ahead of time. A dynamic array expands as you add more elements. So you don't need to determine the size ahead of time.
7. What is the difference between ArrayIndexOutOfBounds and ArrayStoreException?
The ArrayIndexOutOfBoundsException comes when your code tries to access an invalid index for a given array, like a negative index or higher index than length - 1. While, ArrayStoreException comes when you have stored an element of a type other than the type of array, as shown in the above example.
8. How can you check if any subarray of length M repeats at least K times consecutively or not. State the logic to solve this problem.
Initialize a count variable as 0. Run a loop over the array arr[] from 0 to N-M and then perform the following steps:
- If there is a match in the subarray i.e. arr[i] = arr[i + M], then increase count by 1.
- Otherwise, assign value 0 to count variable due to a break in contiguous subarrays.
- If the value of the count variable reaches M * (K – 1), then we get K consecutively equal subarrays of length M. Therefore, print the ‘Yes’ message and come out of the loop.
- If the count value does not reach M * (K - 1) after executing the above steps then print a ‘No’ message.
9. What is the difference between Array and ArrayList?
Array
- It is static in nature.
- It has a fixed size.
- It contains both object and primitive data types of a class.
- It does not have Generic features.
ArrayList
- It is dynamic in nature.
- Its size can vary according to the need.
- It contains only object entries.
- It has Generic features.
10. Is there any difference between int[] a and int a[]?
Both int[] a and int a[] are the ways to declare an array, the only difference between them is that we should use prefix [] if we declare more than one array in a line else the postfix [] one.
11. What are “jagged” arrays in java?
Jagged Arrays are multidimensional arrays that have arrays of variable lengths. For example, we can create a 2D array where the first array contains 5 elements, and the second array contains 4 elements. Following is the example demonstrating the concept of a jagged array. Let's have a look at the code:
public class Main {
public static void main(String[] args){
int[][] two_D_Array = new int[2][];
//first row has 5 columns
two_D_Array[0] = new int[5];
//second row has 4 columns
two_D_Array[1] = new int[4];
int count = 0;
//initializing array
for(int row=0; row < two_D_Array.length; row++){
for(int col=0; col < two_D_Array[row].length; col++){
two_D_Array[row][col] = count++;
}
}
//printing array
for(int row=0; row < two_D_Array.length; row++){
System.out.println();
for(int col=0; col < two_D_Array[row].length; col++){
System.out.print(two_D_Array[row][col] + " ");
}
}
}
Output:
0 1 2 3 4
5 6 7 8
12. How to retrieve the class name of an array?
An array is an object. From the object we can retrieve the class name. We invoke the getClass() and getName() method that retrieves the class name of an array. The getClass() is the method of the Object class that returns the runtime class of the object. While the getName() is the method of the Class class that returns the name of the class/array class.
13. Can you state different ways to copy one array into the other in Java?
There can be four ways to do this operation, these are mentioned below:
- with for loop
public class Main
{
public static void main(String[] args)
{
int first_array[] = {1,2,3,4,5};
//print original array
System.out.println("original array:");
for (int i=0; i
System.out.print(first_array[i] + " ");
// Create an array with same size as first
int copy_array[] = new int[first_array.length];
// first_array is assigned to copyArray; so references point to same location
copy_array = first_array;
// change element of copyArray
copy_array[1]++;
System.out.println("\ncopied array:");
for (int i=0; i
System.out.print(copy_array[i] + " ");
}
}
Output:
original array:
1 2 3 4 5
copied array:
1 3 3 4 5
- with clone() method
class Main
{
public static void main(String args[])
{
int first_array[] = {1,2,3,4,5,6};
int copy_array[] = first_array.clone();
System.out.println("Original first_array:");
for (int i = 0; i
System.out.print(first_array[i]+" ");
}
System.out.println();
System.out.println("Cloned first_array:");
for (int i = 0; i
System.out.print(copy_array[i]+" ");
}
}
}
Output:
Original first_array:
1 2 3 4 5 6
Cloned first_array:
1 2 3 4 5 6
- with Arrays.copyOf() method
import java.util.Arrays;
public class Main
{
public static void main(String args[])
{
// define original array
int[] original_array = new int[] {2,4,6,8};
System.out.println("Original Array:" + Arrays.toString(original_array));
// copying array original_array to copy_array
int[] copy_array = Arrays.copyOf(original_array,4);
System.out.println("Copied Array:" + Arrays.toString(copy_array));
}
}
Output:
Original Array:[2, 4, 6, 8]
Copied Array:[2, 4, 6, 8]
- with System.arraycopy() method
class Main {
public static void main(String[] args) {
//declaring a source array
char[] original_array = {'J', 'a', 'v', 'a'};
char[] copied_array = new char[4];
System.arraycopy(original_array, 0, copied_array, 0,4);
System.out.println("Source array:" + String.valueOf(original_array));
System.out.println("Destination array:"+ String.valueOf(copied_array));
}
}
Output:
Source array:Java
Destination array:Java
14. Is it possible to make an array volatile?
Yes, we can make an array volatile in Java. But we only make the variable that is pointing to array volatile. If an array is changed by replacing individual elements that happen before the guarantee provided by volatile variables will not hold.
15. Explain ArrayStoreException with an example?
ArrayStoreExceptions are raised when we try to store the wrong type of object into an array of objects. It is a class that extends RuntimeException.
public class Test {
public static void main(String args[]) {
Object obj[] = new String[2];
obj[0] = new Integer(0);
}
}
Let’s now have a look into some output questions:
- Predict the output:
#include
int main()
{
int i;
int arr[5] = {1};
for (i = 0; i < 5; i++)
printf("%d ", arr[i]);
return 0;
}
Solution: 1 0 0 0 0
Reason: If you initialise an array with less elements, then the remaining element will be assigned value 0.
- Predict the output:
#include
int main()
{
int i = 0;
printf("Apple");
char p[4] = {'\b', '\t', '\r', '\n'};
for(i = 0 ; i < 4 ; i++) {
printf("%c", p[i]);
}
return 0;
}
Output: Appl
Reason: Apple along with \b\t\r\n is printed.
i.e Apple\b\t\r\n.
Appl\t\r\n.
Appl \r\n.
Appl\n.
Apple → Output
- Predict the output:
#include
int main()
{
int a[2] = {11, 32, 63, 84, 57};
printf("%d", a[3]);
return 0;
}
Output: Garbage Value
Reason: As we can see that the size of the array declared is 2, so it will print garbage value for the elements exceeding 1 index.
- Predict the output:
#include
int main()
{
int i = 0;
char arr[4] = {'\0', '\0', '\0', '\0'};
for(i = 0;i<4;i++)
{
printf("%c", arr[i]);
}
return 0;
}
Output: No Output
Reason: \0 → Null, so nothing will be printed.
Conclusion
These were some of the question types that can be asked in an interview. But learning does not stop here. You can practice more questions with the same concepts for more deep understanding here.