Introduction
If you want to crack Java interviews as a fresher, mastering arrays and ArrayList is crucial. Most IT companies expect you to handle data efficiently, understand memory management, and implement simple algorithms using arrays. They look for your understanding of built-in Java utilities like java.util.Arrays and ArrayList. Being confident in basic sorting, searching, and dynamic array operations can significantly improve your performance in technical interviews.
Frequently Asked Interview Questions
Q1: What is an array in Java?
A1: An array is a collection of similar data types stored in contiguous memory locations. It allows indexing to access elements efficiently.
Q2: How do you declare and initialize an array?
A2: You can declare an array like int[] arr; and initialize it as arr = new int[5]; or int[] arr = {1,2,3,4,5};
Q3: What is a 2D array?
A3: A 2D array is an array of arrays, often visualized as rows and columns, useful for tables, matrices, or grids.
Q4: What is a 3D array?
A4: A 3D array is an array of 2D arrays, often used in simulations, graphics, and multi-layered data storage.
Q5: What are some common methods of the Arrays class?
A5: Common methods include Arrays.sort(), Arrays.binarySearch(), Arrays.fill(), and Arrays.toString().
Q6: How do you sort an array in Java?
A6: Use Arrays.sort(array) to sort the array in ascending order.
Q7: How do you search for an element in a sorted array?
A7: Use Arrays.binarySearch(array, value) for efficient searching.
Q8: What is ArrayList and why is it used?
A8: ArrayList is a resizable array from java.util that allows dynamic addition and removal of elements and provides convenient built-in methods.
Q9: How is ArrayList different from a standard array?
A9: Unlike arrays, ArrayList can dynamically grow or shrink and provides methods like add(), remove(), and get().
Q10: Can ArrayList store primitive types directly?
A10: No. ArrayList can store only objects. Use wrapper classes like Integer, Double, etc.
Q11: How do you iterate through an ArrayList?
A11: You can use a for loop, enhanced for loop, or an iterator to traverse an ArrayList.
Q12: How do you find the size of an array and an ArrayList?
A12: Use array.length for arrays and arrayList.size() for ArrayList.
Q14: What happens if you try to access an array index out of bounds?
A14: Java throws ArrayIndexOutOfBoundsException at runtime.
Q15: How can you convert an array to ArrayList?
A15: Use Arrays.asList(array) method to convert an array to a fixed-size List, then create an ArrayList if needed.
Q16: Can an ArrayList contain duplicate elements?
A16: Yes, ArrayList allows duplicate elements.
Q18: What is a jagged array?
A18: A jagged array is a 2D array where rows can have different lengths.
Q19: Give a real-world example of using ArrayList over arrays?
A19: ArrayList is ideal for a dynamic list of students in a course, where students may join or leave frequently.