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.

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 ()”

9) How to sort an Array?

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

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:-

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.

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?

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

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

2) Using extended new for loop

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

37) How to find the duplicate in an array?

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.

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.

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.

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.

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.

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.

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.

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

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.

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

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.

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

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.

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.

output is

100,100,100,100,100,100

100,100,100,50,50,50


FacebookTwitter
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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