22 Array Concepts Interview Questions Answers in Java

An array is one of the fundamental data structure and most of other advanced data structures like list, 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 on Java interviews. There are two types of question 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 interview and second is usually asked on written test 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 includes both array concepts questions which are based upon how you use an array in Java programming language and second are 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 the question 15 right, he was actually surprised by the fact that you can make an array volatile in Java.

Btw, if you are new into 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 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 structure, 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 question 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 an array like 1-dimension, 2-dimension, an N-dimensional array. No, you cannot change the size of the array once created. If you need a dynamic array, consider using 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 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 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 Generic feature with an array, that's why sometime 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 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 index.


Question 10: What is the difference between an array and a linked list? [answer]
Some 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 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 Arrays.sort() method. Arrays is a utility class which contains lots of static utility method 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 which provides fast copy and also allows you to copy 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 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 java.util package provides 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 which 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 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 array locally inside a method or block, an object is always allocated memory from the heap.

Now that we have seen many array 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 Java Programming Interview Exposed, which contains lots of questions from Java and related technology like  Maven, JUnit, Servlet, JSP, Android, and others.




Array-based Coding Interview Problems

Some array based coding interview questions, which require to build some logic to solve the problem. These questions are mainly asked to check your problem-solving skill apart from your command on 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 integer which 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 pair whose sum is equal to a given number from 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 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 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 first element becomes last and last element becomes first e.g. if 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 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 top 2 numbers from this array like your program should print 6 and 7.


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 question.

You can expect array concept questions on phone round of Java interview and array-based coding problem in face to face interview or written test.

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:

Further Learning
Data Structures and Algorithms: Deep Dive Using Java
Algorithms and Data Structures - Part 1 and 2
Introduction to Algorithms by Thomas H. Corman

 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)
  • Post order 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 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 the Easy to Advanced Data Structures course on Udemy. It's authored by a Google Software Engineer and Algorithm expert and its completely free of cost.

5 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