Categories: Programming

Top 50 Array Interview Questions & Answers

1) What do you mean by an Array?

  • Array is a set of similar data type.
  • Arrays objects store multiple variables with the same type.
  • It can hold primitive types and object references.
  • Arrays are always fixed

2) How to create an Array?

An Array is declared similar to how a variable is declared, but you need to add [] after the type.

Example: int [] intArray;

We can declare Java array as a field, static field, a local variable, or parameter, like any other variable. An array is a collection of variables of that type. Here are a few more Java array declaration examples:

String [] stringArray;

MyClass [] myClassArray;

Same is the case for other programming languages.

3) Advantages and disadvantages of Array?

Advantages:

  • We can put in place other data structures like stacks, queues, linked lists, trees, graphs, etc. in Array.
  • Arrays can sort multiple elements at a time.
  • We can access an element of Array by using an index.

Disadvantages:

  • We have to declare Size of an array in advance. However, we may not know what size we need at the time of array declaration.
  • The array is static structure. It means array size is always fixed, so we cannot increase or decrease memory allocation.

4) Can we change the size of an array at run time?

No we cannot change the array size. Though there are similar data types available which allow a change in size.

5) Can you declare an array without assigning the size of an array?
No we cannot declare an array without assigning size.

If we declare an array without size, it will throw compile time error

Example: marks = new int []; //COMPILER ERROR

6) What is the default value of Array?

Any new Array is always initialized with a default value as follows

  • For byte, short, int, long – default value is zero (0).
  • For float, double – default value is 0.0.
  • For Boolean – default value is false.
  • For object – default value is null.

7) How to print element of Array?

Here is code to print element of the array.

int schoolmarks [] = {25, 30, 50, 10, 5 };

System.out.println (Arrays.toString (schoolmarks));

Output is: [25, 30, 50, 10, 5]

8) How to compare Two Arrays?

If 2 arrays are of the sam size & data type then comparison can be done using “Arrays.equal ()”

int [] num1 = { 1, 2, 3 };

int[] num2 = { 4, 5, 6 };

System.out.println (Arrays. Equals (num1, num2)); //false

Int [] num3 = {1, 2, 3};

System.out.println (Arrays.equals (num1, num3)); //true

9) How to sort an Array?

It is possible using the built static method that is Arrays. sort ().

Int Marks [] = {12, 5, 7, 9};

Arrays.sort(Marks);

System.out.println(Arrays.toString(Marks));//[5, 7, 9, 12]

10) Can we declare array size as a negative number?

No. We cannot declare the negative integer as an array size.

If we declare, there will be no compile-time error.

However, we will get NegativeArraySizeException at run time.

11) When will we get ArrayStoreException?

It is a runtime exception. For example, we can store only string elements in a String Array. If anybody tries to insert integer element in this String Array, then we will get ArrayStoreException at run time.

12) Can we add or delete an element after assigning an array?

No it is not possible.

13) What is the meaning of anonymous array? Explain with an example?

Anonymous array means array without any reference.

Example:-

//Creating anonymous arrays

System.out.println(new int[]{11, 12, 13, 14, 15}.length); //Output : 5

System.out.println(new int[]{31, 94, 75, 64, 41}[1]); //Output : 94 }}

14) Is there any difference between int[] a and int a[]?

No difference both are the legal statement.

15) There are 2 int type array data type. One is containing 50 elements, and another one is containing 30 elements. Can we assign the array of 50 elements to an array of 30 elements?

Yes we can assign provided they should the same type. The compiler will check the only type of the array, not the size.

int[] ab = new int[30];

int[] cd = new int[50];

a = b; //Compiler checks only type, not the size

16) int a[] = new int[3]{1, 2, 3} – is it a right way to declare arrays in java?

No. We should not mention the size of the array when we are providing the array elements.

17) How to copy an array into another array?

Below four tricks are 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

18) What are “jagged” arrays in java?

Jagged Arrays are Arrays are containing arrays of different length. Jagged arrays are also known as multidimensional arrays.

19) When ArrayIndexOutOfBoundsException occurs?

It is a run time exception.

It will occur when the program tries to access invalid index of an array. Index higher than the size of the array or negative index.
20) Can you explain different steps of declaring multidimensional arrays in Java?

//2D Arrays

int[][] twoArray1;

int twoArray2[][];

int[] twoArray3[];

//3D Arrays

int[][][] threeArray1;

int threeArray2[][][];

int[] threeArray3[][];

int[][] threeArray4[];

//4D Arrays

int[][][][] fourArray1;

int fourArray2[][][][];

int[] fourArray3[][][];

int[][] fourArray4[][];

int[][][] fourArray5[];

21) How do we search a specific element in an array?

We can use Arrays.binarySearch() method. This method uses binary search algorithm.

22) If you do not initialize an array what will happen?

Array will have default value.

23) How do we find duplicate elements in an array?

Using Brute Force Method:

In this method, we compare each element of an array with other elements.

If any two elements found equal or same, we declare them as duplicates. Please find below code for the same

public class DuplicatesInArray {

public static void main(String[] args) {

String[] strArray1 = {"abc1", "def1", "mno1", "xyz1", "pqr1", "xyz1", "def1"};

for (int i = 0; i < strArray1.length-1; i++) {

for (int j = i+1; j < strArray1.length; j++) {

if( (strArray1[i].equals(strArray1[j])) && (i != j) ) {

System.out.println("Duplicates : "+strArray1[j]);

}}}} }

Output: Duplicate Element is : def1

Duplicate Element is: xyz1

24) Can we use Generics with the array?

No, we cannot use Generic with an array.

25) How to iterate an array in java?

1) Using normal for loop

public class MainClass1

{

public static void main(String[] args)

{

int[] a1 = new int[]{45, 12, 78, 34, 89, 21};

//Iterating over an array using normal for loop

for (int i = 0; i < a1.length; i++)

{

System.out.println(a1[i]);

}}}

2) Using extended new for loop

public class MainClass1

{

public static void main(String[] args)

{

int[] a2 = new int[]{45, 12, 78, 34, 89, 21};

//Iterating over an array using extended for loop

for (int i: a2){

System.out.println(i);

}}}

26) Where is the memory allocated for arrays in Java?

In Java, memory for arrays is always allocated on the heap as arrays in Java are objects.

27) Can you tell me the class name of an array in Java?

Array is an object. To retirve class name we can use getClass().getName() method on the object.

28) “int a[] = new int[3]{1, 2, 3}” – This a legal way of defining the arrays?

No. We should not declare the size of the array when we are providing the array elements.

29) What is the two-dimensional array?

An array of an array in Java. We can declare them like
int[][] p = new int[3][3] which is a matrix of 3×3.

30) Do we have 3-dimensional arrays in Java?

Yes, Java supports N-dimensional array.

Multi-dimensional array in Java is nothing but an array of array,

Example: 2-dimensional array is an array of 1-dimensional array.

31) Can we make array volatile in Java?

Yes, we can make an array volatile in Java, but we only make the variable which is pointing to array volatile.

32) What will be the output of below code?

int myArr[] = new int [7];

System.out.print(myArr);

Ans: Output will be Garbage value.

myArr is an array variable, myArr is pointing to an array if it is integers.

Printing myArr will print garbage value. It is not same as printing myArr[0].

33) What is the step to access elements of an array in Java?

We can access using “index”.

Index starts from Zero(0), so the first element is stored in location zero and the last element will be Array.length – 1.

Example:-String strArr[] = new String []{“A”, “B”, “C”, “D”, “E”};

strArr[0] means “A” and strArr[2] means “C”.

34) Can you tell me the differences between Array and ArrayList?

Array ArrayList
The array is static with a fixed size which cannot be changed once delared. ArrayList is not static but dynamic in size. As elements added to an ArrayList, its capacity or size grows automaticically.
It contains both primitive data types and objects of a class. ArrayList does not contain the primitive data types but contains object entries.
Array does not have Generics feature. ArayList has Generics feature.

35) We know that Arrays are objects so why cannot we write strArray.length()?

Arrays are object references like classes in Java. We can use the methods of Object like toString () and another one hashCode () against Array. Length is a data item of an array and so it is not a method. That’s why we are using strArray.length.

36) How to find the missing element in integer array of 1 to 7?

Solutions to solve this problem is to calculate sum of all numbers in the array

and compare with an expected sum, the difference would be the missing number.

int ar [] = new int[]{1,2,3,5,6,7};

  • Get the sum of numbers
  • total = n*(n+1)/2
  • Subtract all the numbers from sum and
  • you will get the missing number.
  • According to below logic sumOfNnumberss is 7*(7+1)/2=28

sumOfElements = 1+2+3+5+6+7=24

missing element is = 28-24=4

int n = ar.length+1;

int total = n*(n+1)/2;

for(int i =0;i<ar.length;i++){

total -=ar[i];}

System.out.println(total);

37) How to find the duplicate in an array?

String str = "HI RAHUL I AM FINE RAHUL"; // String with a duplicate word.

String[] words = str.split(" "); // Splitting and converting to Array .

for(int i = 0; i < words.length; i++){ //iterating array inside for loop

for(int j = i+1; j < words.length; j++){ //iterating same array inside another for loop

if (words[i].equals(words[j])){ // Using equal method i am verifying which word is repeating . System.out.println( words[i]); // here it will print duplicate .

}}}

38) How to check array contains value or not?

Here is a String[] with values

public static final String[] myNames = new String[] {“B”,”A”,”K”,”C”};

If myNames contains that value then it will return true otherwise false.

Here is two methods isExists() and contains()

both the methods return true if the value is available otherwise false.

First Method

It is converting an array to ArrayList.

After that it will test if an array contains any value then it will return true otherwise false.

public static <T> boolean isExists(final T[] array, final T object) {

return Arrays.asList(array).contains(object); }

Second Method

This method loop through an array and use equal() method to search element.

This actually performs a linear search over an array in Java. It will return true if an array has provided value.

public static <T> boolean contains(final T[] array, final T v) {

for (final T e : array) { if (e == v || v != null && v.equals(e)) {

return true;

} }

return false;

} }

39) How to get largest and smallest number in an array?

Ans: Logic of this problem:

  • We use two variables to store largest and smallest number.
  • First, we initialize largest with Integer.MIN_VALUE and
  • Next, we initialize smallest with Integer.MAX_VALUE.
  • In each iteration of the for loop, we will compare present number with largest and smallest number, and we will update
  • If a number is larger than largest, then it cannot be smaller than smallest. That means no need to check if the first condition is true,
  • We will use the if-else code block, where else part will only execute if the first condition is false means not true.
import java.util.Arrays;

public class MaximumMinimumArrayExample{

public static void largestAndSmallest(int[] numbers) {

int largest = Integer.MIN_VALUE;

int smallest = Integer.MAX_VALUE;

for (int number : numbers) {

if (number > largest) {

largest = number;

}

else if (number < smallest) {

smallest = number;

} }
System.out.println("Largest is : " + largest);

System.out.println("Smallest is : " + smallest); } }

40) How to do the intersection of two sorted arrays?

Ans: Logic: print the element if the element is present or available in both the arrays.

  • Use two index variables i and j, after that initial the values i = 0, j = 0
  • If arr01 [i] is smaller than arr02 [j] then increment i.
  • If arr01 [i] is greater than arr02 [j] then increment j.
  • If both are same then print any of them and increment both i and j.
public static void getIntersection(int arr01[], int arr02[], int m, int n){

int i = 0, j = 0;

while (i < m && j < n){

if (arr01[i] < arr02[j])

i++;

else if (arr02[j] < arr01[i])

j++;

else{

System.out.print(arr02[j++]+" ");

i++;

}

}

}

public static void main(String args[]){

int arr01[] = {1, 2, 4, 5, 6};

int arr02[] = {2, 3, 5, 7};

int m = arr01.length;

int n = arr02.length;

getIntersection(arr01, arr02, m, n);

}

41) How to get top two numbers from an array?

Ans: Logic is:

  • We will assign first variable max01 with Integer.MIN_VALUE

Moreover, second variable max02 with same as max01 that is Integer.MIN_VALUE.

  • We will iterate this array and compare each number with max01 and max02,
  • If current number is greater than max1 then assign max01 = number and max02 = max1.
  • Else if it is only greater than max02 then we will only update max02 with the current number.
  • At the end of an iteration, max01 and max02 points to top two numbers from given array.
import java.util.Arrays;

public class TopTwoMaximumNumbers{

public static void main(String args[]) {

topTwoNumbers(new int[]{20, 34, 21, 87, 92, Integer.MAX_VALUE});

topTwoNumbers(new int[]{0, Integer.MIN_VALUE, -2});

topTwoNumbers(new int[]{Integer.MAX_VALUE, 0, Integer.MAX_VALUE});

topTwoNumbers(new int[]{1, 1, 0}); }

public static void topTwoNumbers(int[] numbers) {

int max01 = Integer.MIN_VALUE;

int max02 = Integer.MIN_VALUE; for (int number : numbers) {

if (number > max01) { max02 = max01; max01 = number; }

else if (number > max02) { max02 = number; } }

System.out.println("First largest number is : " + max01);

System.out.println("Second largest number is : " + max02); } }

42) How to cut or remove an element from the array?

Ans: Logic is: We can remove or cut an element using Apache Commons ArrayUtils based on an index.

ArrayUtils has several overloaded remove() method.

import java.util.Arrays;

import org.apache.commons.lang.ArrayUtils;

public class RemoveFromArray{

public static void main(String args[]) {

//let's create an array for demonstration purpose

int[] testArr = new int[] { 10, 102, 13, 14, 105};

System.out.println("Array size : " + testArr.length );

System.out.println("Find Contents : " + Arrays.toString(testArr));

//let's remove or delete an element from Array using Apache Commons ArrayUtils

testArr = ArrayUtils.remove(testArr, 2); //removing element at index 2

//Size of array must be 1 less than original array after deleting an element

System.out.println("Size of array after removing : " + testArr.length);

System.out.println("Content of Array : "+ Arrays.toString(testArr));

} }

43) What is the logic to reverse the array?

Ans: Logic: print the element in reverse order.

  • Declare a String Array String[] s = new String[]{“My”,”Leg”,”is”,”cut”};
  • Iterate it using for loop get all elements in reverse order means end point to start point.
public static void main(String[] args)

{String[] s = new String[]{"My","Leg","is","cut"};

for(int i=s.length-1; i>=0; i--){

System.out.println("reverse "+s[i]);}}

44) How do you find the second largest element in an array of integers?

Ans: Logic is:

  • Iterate the given array using for loop.
  • (first if condition arr[i] > largest):
  • If current array value is greater than largest value then
  • Move the largest value to secondLargest and make current value as largest
  • (second if condition arr[i] > secondLargest )
  • If the current value is smaller than largest and

greater than secondLargest then the current value becomes

public static void main(String[] args) {

int myArr[] = { 14, 46, 47, 86, 92, 52, 48, 36, 66, 85 };

int largest = myArr[0];

int secondLargest = myArr[0];

System.out.println("The given array is:" );

for (int i = 0; i < myArr.length; i++) {

System.out.print(myArr[i]+"\t");

}

for (int i = 0; i < myArr.length; i++) {

if (myArr[i] > largest) {

secondLargest = largest;

largest = myArr[i];

} else if (myArr[i] > secondLargest) {secondLargest = myArr[i];

}}

System.out.println("\nSecond largest number is:" + secondLargest);

}

45) Write a program to sum values of given array.

Ans: Logic is:

  • Declare and assign int variable that is sum =0.
  • Iterate the given array using for loop.
  • Add all the array element and keep in this variable that is the sum.
Public static void main(String[] args) {

int my_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

int sum = 0;

for (int i: my_array)

sum += i;

System.out.println("The sum is " + sum);

}

46) How do you separate zeros from non-zeros in an array?

Ans: Logic is:

  • Initializing counter to 0
  • Traversing inputArray from left to right
  • If inputArray[i] is non-zero
  • Assigning inputArray[i] to inputArray[counter]
  • Incrementing the counter by 1
  • Assigning zero to remaining elements
Public class SeparateZerosFromNonZeros

{ static void moveZerosToEnd(int inputArray[]) { int counter = 0;

for (int i = 0; i < inputArray.length; i++)

{

if(inputArray[i] != 0) {

inputArray[counter] = inputArray[i];

counter++;

} }

while (counter < inputArray.length) {

inputArray[counter] = 0;

counter++; }

System.out.println(Arrays.toString(inputArray));

}

public static void main(String[] args) {

moveZerosToEnd(new int[] {12, 0, 7, 0, 8, 0, 3});

moveZerosToEnd(new int[] {1, -5, 0, 0, 8, 0, 1});

moveZerosToEnd(new int[] {0, 1, 0, 1, -5, 0, 4});

moveZerosToEnd(new int[] {-4, 1, 0, 0, 2, 21, 4});

} }

47) Write a program to insert an element and in the specific position in the array?

Ans: Logic is:

  • Insert an element in 3rd position of the array (index->2, value->5)
  • Iterate the given array in reverse order using for loop.
  • Now insert given position and value after for loop.
Public static void main(String[] args) {

int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};

int Index_position = 2;

int newValue = 5;

System.out.println("Original Array : "+Arrays.toString(my_array));

for(int i=my_array.length-1; i > Index_position; i--){

my_array[i] = my_array[i-1];
}my_array[Index_position] = newValue;

System.out.println("New Array: "+Arrays.toString(my_array));

}

48) How to get the index of an array element?

Ans: Logic is:

  • In each step, it checks the input key value with the value of the middle element of an array.
  • If the keys match then it will return the position. In another case, if the key is less than the middle element’s key,
  • Then it will repeat the while loop. If the remaining array searched and it reduced to zero it will return -1 means not found
public static int findIndex (int[] my_array, int t) {

int startPoint = 0;

int endPoint = my_array.length - 1;

while (startPoint <= endPoint) {

int mid = (startPoint + end) / 2;

if (key == my_array[mid]) {

return mid;

}

if (key < my_array[mid]) {

endPoint = mid - 1;
} else {

startPoint = mid + 1;

}

}

return -1;

}

Public static void main(String[] args) {

int[] arr = {2, 4, 6, 8, 10, 12, 14, 16};

System.out.println("Key 14's position: "findIndex(arr, 14));

int[] arr1 = {6,34,78,123,432,900};

System.out.println("Key 432's position: "+findIndex(arr1, 432));

}

49 Can we extend an array after initialization?

Ans: Logic is: We can extend an array after initialization by adding a new array.

Please find below example.

Public static void main(String[] args) {

String [] names = new String[] { "A", "B", "C" };

String [] extended = new String[5];

extended [3] = "D";

extended [4] = "E";

System.arraycopy(names, 0, extended, 0, names.length);

//here we are extending with new array extended[3] and extended[4].

for (String str: extended){

System.out.println(str);

}

}

output is A,B,C,D,E.

50) How to fill element (initialize at once) in an array?

Ans: This example fill(initialize all the elements of the array in one short) an array by using

Array.fill(array name,value) method and

Array.fill(array name, starting index, ending index, value)

the method of Java Util class.

import java.util.*;

public class FillTest {

public static void main(String args[]) {

int array[] = new int[6];

Arrays.fill(array, 100);

for (int i = 0, n = array.length; i < n; i++) {

System.out.println(array[i]);

}

System.out.println();

Arrays.fill(array, 3, 6, 50);

for (int i = 0, n = array.length; i< n; i++) {

System.out.println(array[i]);}}}

output is

100,100,100,100,100,100

100,100,100,50,50,50

Share

Leave a Reply

Your email address will not be published. Required fields are marked*