Top 22 Array Concepts Interview Questions Answers in Java

An array is one of the fundamental data structures and most of the other advanced data structures like lists, hash tables are built using arrays.  Good knowledge of fundamental data structures like the array, linked list, a binary tree is not just essential for writing better code but also doing well on Programming Job interviews. Array-based questions are quite popular in Java interviews. There are two types of questions you will find, first which are based upon array implementation in Java, and second which are based upon how to use an array data structure to solve some coding problems. The first type of question is quite popular in the telephonic round of Java interviews and the second is usually asked on written tests and face-to-face interviews.

In this article, I am going to share some of the frequently asked array-based questions from Java interviews, which include both array concepts questions which are based upon how you use an array in Java programming language, and second is general array-based coding problems

These questions are mostly collected from Java interviews for junior and intermediate programmers, who have 0 to 5 years of working experience in Java. Some tricky questions like the question no 2 and 15 are also good for senior and more experienced Java professionals.

In fact, one of my friends didn't get question 15 right, he was actually surprised by the fact that you can make an array volatile in Java.

Btw, if you are new to the Java Programming world, there is no better way to get familiar yourself with the essential data structure in Java by joining The Complete Java MasterClass, which covers the Java Collection framework, where you can find the standard implementation of all important data structure in Java.





Java Array Concept Interview Questions

Here are some interview questions based upon the array data structure in Java. You need to have good knowledge of how an array is implemented and work in Java to answer these questions.

Since an array is one of the most used data structures, it's expected from programmers of all levels (including beginners and experienced) to have a good grasp of array concepts.

These questions are mostly asked in a telephonic round of Java interviews. Your answer to these questions must be focused and to the point, without any added syntactic sugar.


Question 1: What is an array? Can you change the size of the array once created? [answer]

An array is a fundamental data structure to store objects and primitive values. You have different types of array, like 1-dimension, 2-dimension, and N-dimensional array. No, you cannot change the size of the array once created. If you need a dynamic array, consider using the ArrayList class, which can resize itself.

Array concept interview questions and answers in Java




Question 2: Can you store String in an array of Integer in Java? compile-time error or runtime exception? [answer]

This is a tricky question. The answer is both yes and no. You cannot store a string in an array of primitive int, it will result in a compile-time error as shown below, but if you create an array of Object and assign String[] to it and then try to store Integer object on it.

The compiler won't be able to detect that and it will throw ArrayStoreExcpetion at runtime.

int[] primes = new int[10];
primes[0] = "a";  //compile time error
        
Object[] names = new String[3];
names[0] = new Integer(0); // ArrayStoreException at runtime



Question 3: What is the difference between ArrayIndexOutfOBounds and ArrayStoreException? [answer]

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.


Question 4: Can you use Generics with an array? [answer]

No, you cannot use the Generic feature with an array, that's why sometimes List is a better choice over an array in Java, which is also recommended by Joshua Bloch in his class Java book, Effective Java, a must-read for writing good code in Java.




Question 5 : Is it legal to initialize an array int i[] = {1, 2, 3, 4, 5}; [answer]

Yes, it's perfectly legal. You can create and initialize an array in the same line in Java.


Question 6: Difference between b[] and []b  in Java? [answer]

You can declare an array in Java by either prefixing or suffixing[] with a variable. There is not much difference between them if you are not creating more than one variable in one line, but if you do then it creates different types of variables, as shown in the following example :

int a[], b; // first is int array, second is just int variable
int[] c, d; // both c and d are integer array


Question 7: What is a two-dimensional array in Java? [answer]

An array of the array in Java.  You can declare them like int[][] primes = new int[3][3] which is a matrix of 3x3.


Question 8: Do you have a three-dimensional array in Java? [answer]

Yes, Java supports the N-dimensional array. Actually, a multi-dimensional array in Java is nothing but an array of array, for example, a two-dimensional array is just an array of a one-dimensional array.


Question 9: How to iterate over an array in Java? [answer]

You can either use classical for loop with the index or advanced foreach loop introduced in Java 5 to iterate over an array in Java. If you need the index to select some element or do something else, use for loop otherwise advanced foreach loop is better. It's less error-prone as you don't need to deal with the index.


Question 10: What is the difference between an array and a linked list? [answer]

One key difference between an array and linked list data structure is, Array requires contiguous memory for its element but linked list elements can be scattered in memory, which means it would be difficult to create a big array but your linked list can grow easily.

An array is good for searching elements if you know the index, but adding and removing elements in an array is expensive as compared to the linked list.  If you are interested, you can further check out Data Structures and Algorithms: Deep Dive Using Java course on Udemy to learn more about basic data structure and algorithms.

What is the difference between an array and a linked list?



Question 11: How to sort an array in Java? [answer]

You can sort an array in Java by using the Arrays.sort() method. Arrays is a utility class that contains lots of static utility methods to operate on arrays. This method is overloaded and you can optionally provide a Comparator implementation to sort the array in a custom order.


Question 12: How to copy an array in Java? [answer]

You can either manually copy elements of an array by iterating over them, or you can use System.arrayCopy() method to copy elements from one array to another. This is a powerful method that provides fast copy and also allows you to copy the entire or part of the array.


Question 13: How to access elements of an array in Java? [answer]

You can access elements of an array using the index in Java. It starts from 0, so the first element is stored in location zero and the last element has an index length - 1. Trying to access an invalid index in Java, like a negative index or index higher than size will result in ArrayIndexOutOfBoundsException in Java.


Question 14: How to search an array to check if an element exists there? [answer]

You can search an element inside an array by using either a linear search or binary search. Later is faster but you need to sort the array before performing a binary search on it.

The Arrays class from the java.util package provides a binarySearch() method to search an element in an array. Alternatively, you can also convert the array to ArrayList and use its contains() method to find out if an element exists or not.

But, if you want to do it without using an API method, you can also check out this post to implement the binary search algorithm in Java.





Question 15: Can you make an array volatile in Java? [answer]

This is another tricky question in Java. Yes, you can make an array volatile in Java, but you 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.

Anyway, if you are seriously preparing for a Java interview then you have to do more than just preparing for array-based questions. I suggest you take a look at this Java Interview Guide, which contains 200+ Java questions and answers, good enough to clear any Java interview.


Question 16: Where does an array stored in memory? [answer]

An array is created in the heap space of JVM memory. Since an array is an object in Java, even if you create an array locally inside a method or block, an object is always allocated memory from the heap.

Now that we have seen many arrays concept-based questions from Java interviews, let's move on to the second part of this article, where we'll see some array-based coding problems.

Btw, If you want to prepare more Java-specific questions then you can also take a look at the Java Programming Interview Exposed, which contains lots of questions from Java and related technology like  Maven, JUnit, Servlet, JSP, Android, and others.





Array-based Java Coding Interview Problems

Some array-based coding interview questions, which require building some logic to solve the problem. These questions are mainly asked to check your problem-solving skills apart from your command of a programming language.

Actually, once you know the logic, you can solve these problems in any programming language like C, C++, Python, Ruby or JavaScript, or even Haskell and Golang, it's all up to you.


Problem 1: How to find a missing number in an array of 1 to 100 in Java? [solution] You have given an array of integers that contains numbers from 1 to 100, but exactly one number is missing, how do you find that number? You can use an additional data structure.


Problem 2: How do you find all pairs whose sum is equal to a given number from an integer array in Java? [solution] You have given an array of int primitives and a number, you need to find all pairs in an array whose sum is equal to a given number e.g. if an array is {1, 2, 3,  4, 5} and given sum is 6 then your program should return {2, 4} and {1, 5}.

The classic Cracking the Coding Interview book by Gayle Laakmaan Mcdowell also has a solution for this solution and you can find more coding problems there.

Java array interview questions with answers



Problem 3:  How do you remove duplicates from the array in Java? [solution] You have given an array, which could be an array of numbers or Strings, or any objects. Some objects are added multiple times in an array, you need to remove those elements from an array. You don't know how many duplicates are there. You can use an additional data structure and memory to solve this problem.


Problem 4: How do you reverse an array in Java? [solution]
Given an array of String or integer, how do you reverse the array, so that the first element becomes last and the last element becomes first like if the given array is {1, 2, 3, 4} then your program should reverse it as {4, 3, 2, 1}. You can use additional memory but reversing the array in place will get a bonus point.


Problem 5: How to find duplicates numbers in an array of integers in Java? [solution] You have given an array {1, 1, 2, 3, 3, 4}, write a program to return duplicate elements like 1 and 3 because they have appeared more than once in an array.


Problem 6: How to find the top two numbers from an integer array in Java? [solution] You have given an integer array e.g. { 3, 4,  5, 6, 7}, you need to find the top 2 numbers from this array like your program should print 6 and 7.

Top 22 Array Concepts Interview Questions Answers in Java



That's all about array concepts interview questions in Java. I have shared questions on array fundamentals in Java as well as some array-based coding problems from interviews. It's important to practice both kinds of questions.

You can expect array concept questions on the phone round of Java interviews and array-based coding problems in the face-to-face interviews or written tests.

These questions are mainly for beginner and intermediate Java programmers, someone who has 2 to 5 years of experience working in core Java. Array concept questions are mainly for Junior programmers and freshers. If you think your data structure and algorithm skill is lacking, you can also check out the following resource to revise algorithm concepts:



 Other Data Structure and Algorithms  You may like
  • 10 Courses to Crack Programming Job Interviews (courses)
  • 50+ Data Structure and Algorithms Problems from Interviews (list)
  • 5 Books to Learn Data Structure and Algorithms in-depth (books
  • How to reverse an array in Java? (solution)
  • 75+ Coding Interview Questions for Programmers (questions)
  • How to remove duplicate elements from the array in Java? (solution)
  • How to implement a recursive preorder algorithm in Java? (solution)
  • How to implement a binary search tree in Java? (solution)
  • Postorder binary tree traversal without recursion (solution)
  • How to print leaf nodes of a binary tree without recursion? (solution)
  • Recursive Post Order traversal Algorithm (solution)
  • My favorite free courses to learn data Structure in-depth (FreeCodeCamp)
  • Iterative PreOrder traversal in a binary tree (solution)
  • How to count the number of leaf nodes in a given binary tree in Java? (solution)
  • Recursive InOrder traversal Algorithm (solution)
  • 10 Free Data Structure and Algorithm Courses for Programmers (courses)
  • 100+ Data Structure Coding Problems from Interviews (questions)

Thanks for reading this article so far. If you like this Java Array tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a comment.

P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check these free data structure and algorithms courses on Udemy. It's authored by a Google Software Engineer and Algorithm expert and it's completely free of cost.

11 comments:

  1. I was asked, can you declare two dimensional array without speciffying second dimension in Java?
    Answer is yes, its possible becaues two dimentional arrys are nothing but array of array in Java and you can later store array object of arbitrary length into 2D arrays. Only first dimension is mandatory while declaring 2D array in Java.

    ReplyDelete
  2. Regarding question "How to copy array in Java?"
    You can also use clone() and Arrays.copyOf() method to make copy of an array in Java. for example
    int[] even = {2, 4, 6, 8}
    int[] integers = even.clone()

    will create another array of same length and same content as even but a differnet object in heap and assign to reference variable integers.

    ReplyDelete
  3. Problem 3 : How do you remove duplicates from array in Java

    With java 8 :

    List numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
    numbers.stream().distinct().forEach(System.out::print);

    ReplyDelete
  4. Problem 4 : How do you reverse an array in Java?
    System.out.println("sorted");
    list.stream().sorted().forEach(System.out::println);
    System.out.println("reverse");
    list.stream().sorted( (w,b) -> b.compareTo(w) );

    ReplyDelete
  5. @Farvher, thank you, very interesting solutions, learning Java 8 with these kind of programming problems seems real fun :-)

    ReplyDelete
  6. Thanks for sharing such an useful stuff

    ReplyDelete
    Replies
    1. Thanks @Unknown that you find these array concepts questions useful .

      Delete
  7. Linked List
    --------------

    Palindrome List
    Implement method isPalindrome with algorithm to check if a linked list is a palindrome.

    Examples
    0->1->2->1->0 -> true


    Reverse Linked List
    Given a singly linked list, write a method reverseList to reverse the list and return new head.

    Examples
    1->2->3->4->5->6 -> 6->5->4->3->2->1


    Remove Duplicates
    Write method removeDuplicates to remove duplicates from an unsorted linked list.

    Examples
    1->2->3->4->3->3 -> 1->2->3->4

    Insert Node at Tail
    Write a method insertAtTail to insert a node at the end of a singly linked list. Return the head of the modified list.

    Examples
    1->2->3->4->5->6, 7 -> 1->2->3->4->5->6->7

    Return Kth to Last
    Implement method kthToLast with algorithm to find the kth to last element of a singly linked list.

    Examples
    1->2->3->4->5->6, 3 -> 3
    Notes
    If index is absent, return 0.


    Delete List Tail Node
    Given a singly linked list, write a method deleteAtTail to delete its last node and return the head.

    Examples
    1->2->3->4->5->6 -> 1->2->3->4->5

    Delete List Head Node
    Given a singly linked list, write a method deleteAtHead to delete its head node and return the new head.

    Examples
    1->2->3->4->5->6 -> 2->3->4->5->6


    Find Middle Node
    Given a singly linked list, write a method findMiddleNode to find and return the middle node of the list.

    Examples
    1->2->3->4->5 => 3->4->5
    1->2->3->4->5->6 => 4->5->6

    ReplyDelete
  8. Insert Node at Head
    Write a method insertAtHead to insert a node at the front of a singly linked list. Return the head of the modified list.

    Examples
    1->2->3->4->5->6, 7 -> 7->1->2->3->4->5->6


    Sum Lists
    You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write method addLists that adds the two numbers and returns the sum as a linked list.

    Examples
    7->1->6, 5->9->2 -> 2->1->9 (617 + 295 = 912)


    Sum Lists 2
    You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in forward order, such that the 1’s digit is at the tail of the list. Write method addLists that adds the two numbers and returns the sum as a linked list.

    Examples
    6->1->7, 2->9->5 -> 9->1->2 (617 + 295 = 912)


    Delete Node at Middle
    Given a singly linked list, write a method deleteAtMiddle to delete the node at a given position (starting from 1 as the head position) and return the head of the list. Do nothing if the input position is out of range.

    Examples
    1->2->3->4->5->6, 3 -> 1->2->4->5->6


    Is List cyclic
    Given a singly linked list, write a method isCyclic to check if the list has cycles. The space complexity can be O(n). If there is a cycle, return true otherwise return false. Empty lists should be considered non-cyclic.

    Examples
    1->2->3->4->5->6->1 -> true

    Add Two Linked List Numbers
    Given two integers represented as linked-lists, find their sum and return it in the form of linked list.

    You can assume that the input integers are non negative and the digits stored in the linked lists are in the reverse order.

    Examples
    1->2->3, 1->2->3 -> 2->4->6
    9->9, 9->8 -> 8->8->1

    ReplyDelete
  9. Merge k Sorted Linked Lists
    Write a method mergeKLists to merge k Sorted LinkedList.

    Why would you ever want to do that? Well, if you’re dealing with a list of over 200 Million Integers that needs to be sorted, an efficient approach might involve splitting up the massive list into k smaller lists, sorting each list in memory and then combining the sorted lists to re-create the original list, albeit sorted.

    Example
    * 1->2->13->20
    * 1->20->35->40
    * 5->6->12->18

    => 1->1->2->5->6->12->13->18->20->20->35->40

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.