Java array is the most important and commonly asked topic in programming interview questions. The Tutorial shares the top 30 java array interview questions and answers for IT exam or interview preparation. Java Array is one of the used data structure in java programming and thus important for beginners and experienced programmers to possess clarity on java array implementation.
1. What is an Array in java ?
- Java Array is the data structure with the collection of elements to organize and store the objects sequentially.
- Array in java uses index for each position. Array Index starts from 0 position.
- Array stores the collection of elements with the similar data types.
- Array are fixed in length and thus not expandable in size.
- Array objects in java are stored in the heap memory and not on the stack.
- Arrays can be categorized as 1-dimensional array, 2 -dimensional array, N-dimensional array.
- Arrays in java are implemented in other data structures like List, Heap, Hash Tables, Queues, Strings.
- The simplest example of Array data structure could be a linear array (also called 1-dimensional array)
2. What are the advantages and disadvantages of array in java?
Advantages:
- Arrays in java provides fast lookup (retrieval / traversal) of elements using index.
- Array retrieval takes o(1) times irrespective of the array length
- Appending array with new element at the end of the array works faster , takes O(1) time.
Disadvantages:
- Arrays in java are of fixed length and thus cannot be expandable at run time.
- Collection of elements in array should be of same data type.
- Array insertion and Array deletion take O(n) time and thus makes the operation costlier with respect to execution time.
Below given are the Array operations and their execution time.
Array Operations | Array Execution Time |
Array Space | O(n) |
Array Lookup / Retrieval | O(1) |
Array Append (last element) | O(1) |
Array Insertion | O(n) |
Array Deletion | O(n) |
3. How the array is stored ?
Array is an object in the java and it is being stored in the heap memory in the JVM
4. Can the array be declared without size?
No. Array is fixed length in java and need to be initialized with size.
5. Does Array allows adding string value into Integer Array ?
We know that Arrays in java is the collection of elements with the same data type. Thus , storing string value in Integer Array gives the compile time error.
package core.java.oracleappshelp.array; public class AssingStringToIntArray { public static void main(String args[]) { int[] assingIntValue = new int[5]; assingIntValue[0] = "Mohit"; //compile time error } }
6. Explain ArrayStoreException and hierarchy in Java Array ?
The ArrayStoreException exception occurs when the object is stored with a different data type which is not same as per the defined array object. Let’s consider another example. Create an Array of object assigned with String [ ] . Add the integer value. In this case, although compiler doesn’t give compile time error but it does generates ArrayStoreException at the run-time.
package core.java.oracleappshelp.array; public class ArrayStoreExceptionExample { public static void main(String[] args) { Object[] students = new String[10]; students[0] ="Rohit"; students[1] ="Mohit"; // assignment of integer generates ArrayStoreException at run time. students[2] = new Integer(0); } } Program Output: Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer at core.java.oracleappshelp.array.ArrayStoreExceptionExample.main(ArrayStoreExceptionExample.java:8)
ArrayStoreException Class Hierarchy:
java.lang.Object ↳ java.lang.Throwable ↳ java.lang.Exception ↳ java.lang.RuntimeException ↳ java.lang.ArrayStoreException
Constructors of ArrayStoreException:
- ArrayStoreException(): Constructs an ArrayStoreException instance with no detail message.
- ArrayStoreException(String storeExcMessage): Constructs an ArrayStoreException instance with the specified message
7. What are the common errors / exceptions in Arrays ?
- NullPointerException : when value accessed is retrieved as NULL at run-time.
- NegativeArraySizeException when array is identified with a negative size
- ArrayIndexOutOfBoundsException : When array is accessed or modified with a invalid index or index value is idnetiifed more than the array size.
- ClassCastException :
package core.java.oracleappshelp.array; public class ArrayClassCastExceptionExample { public static void main(String[] args) { Object storeIntValues = new Integer(10); System.out.println((String)storeIntValues); } } Program Output: Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at core.java.oracleappshelp.array.ArrayClassCastExceptionExample.main(ArrayClassCastExceptionExample.java:6)
ArrayStoreException: Refer the above question explained with the example.
8. What is the default array value for different data types ?
Java Data Type | Default Array Value |
byte, short,int,long | 0 |
float, double | 0.0 |
boolean | false |
Object | null |
9. Is Generics use supported in array ?
No
10. Define anonymous array in java ?
The Array which does not have a name or reference is termed as anonymous array in java.
new String[]{“Open”, “Close”, “Save”};
new int[] {100,200,300,400,500};
11. What are jagged arrays in java ?
Arrays containing arrays with different size are termed as jagged arrays.
Example: Multi-dimensional arrays included Jagged arrays.
12. Can the array with higher size be assigned to an array with less size ?
Yes, arrays support this feature. If an array1 has size of 10 elements and array2 has size of 5 elements, then array1 can be assigned to array2 even though it has less element size as array validation checks for the array to be of same data type and does not validate on the array size during compilation.
import java.util.*; public class CopyLargeArrayToSmallArraySize{ public static void main(String args[]) { int[] arrayWithLessSize = new int[20]; int[] arrayWithLargeSize = new int[40]; arrayWithLessSize = arrayWithLargeSize; System.out.println(arrayWithLessSize.length); } }
13. Write a java program to sort an array and print in java ?
The below java program uses Arrays.sort( ) method to sort the numbers in array
package core.java.oracleappshelp.array; import java.util.Arrays; public class arraySortingInJava { public static void main(String[] args) { int[] numberList = { 700, 100,500,900,50 }; Arrays.sort(numberList); for (int traverseList : numberList) System.out.print(traverseList +" "); } } Array Program Output: 50 100 500 700 900
14. what are the possible ways to copy array content from one array to another ?
The below given methodologies can be applied in java for copy array content
- Using for loop to traverse and copy the content
- Using clone( ) method
- Using Arrays.copyOf( ) method
- Using System.arraycopy ( ) method
15. Describe the differences between Array and ArrayList ?
http://oracleappshelp.com/main-differences-between-array-and-arraylist-in-java/
16. What will be the ouput for an Array which is not initialized ?
The Array will be assigned with the Default Value based on the Array Data Type
17. Write a java program to identify duplicate array elements in java ?
package core.java.oracleappshelp.array; public class IdenitfyDuplicateArrayElements { /* Method Name - getDuplciateArrayElements * Java method to identify the duplicate array elements from the received any input. */ public static void getDuplciateArrayElements(String[] studentNames) { for(int outerLoop=0; outerLoop < studentNames.length-1; outerLoop++){ for(int innerLoop=outerLoop+1; innerLoop < studentNames.length; innerLoop++) { if(studentNames[outerLoop].equals(studentNames[innerLoop]) && outerLoop!=innerLoop ) { System.out.println("Idneitifed duplicate array element is : "+ studentNames[innerLoop]); } } } } public static void main(String args[]) { String[] studentNames = {"Roit", "Mohit", "Vinay", "Mohit", "Akshay" }; getDuplciateArrayElements(studentNames); } }
18. Is an array thread-safe in java ?
- Array operation is java have their complexity.
- Array Retrieval is thread-safe.
- Array insertion, updation and deletion are not thread-safe.
19. Can array be made volatile ?
Only variable representing an array can be made volatile
20. Write a java program to check if the given two arrays are equal or not ?
The below given program uses Arrays.equal( ) method to validate if the comparison of two arrays is equal or not.
package core.java.oracleappshelp.array; import java.util.Arrays; public class ArraysComparison { public static void main(String[] args) { int[] arrayObject_1 = { 700, 100,500,900,50 }; int[] arrayObject_2 = { 700, 100,500,900,50 }; int[] arrayObject_3 = { 100, 200,500,900,50 }; System.out.println(" Is Array Object 1 Equals to Array Object 3" + Arrays.equals(arrayObject_1 , arrayObject_2)); System.out.println(" Is Array Object 1 Equals to Array Object 3" + Arrays.equals(arrayObject_1 , arrayObject_3)); System.out.println(" Is Array Object 2 Equals to Array Object 3" + Arrays.equals(arrayObject_2 , arrayObject_3)); } } Array Program Output: Is Array Object 1 Equals to Array Object 3 true Is Array Object 1 Equals to Array Object 3 false Is Array Object 2 Equals to Array Object 3 false
21. How many ways multi dimesional arrays can be created in java ?
Multi Dimesional arrays in java could be 2D, 3D and 4D . Below given are the few examples of creating multi dimesional arrays in different ways
/* 2 Dimesional Arrays */
int[][] twoDimesionalArray1; int twoDimesionalArray2[][]; int[] twoDimesionalArray3[];
/* 3 Dimensional Arrays */
int[][][] threeDimesionalArray1; int threeDimesionalArray2[][][]; int[] threeDimesionalArray3[][]; int[][] threeDimesionalArray4[];
/*4 Dimesional Arrays */
int[][][][] fourDimesionalArray1; int fourDimesionalArray2[][][][]; int[] fourDimesionalArray3[][][]; int[][] fourDimesionalArray4[][]; int[][][] fourDimesionalArray5[];
22. How to convert an array to arrayList in java ?
The below apprach can be used for converting an array to arrayList in java
- Using Arrays.asList() method
String studentNames[]={"Mohit", "Rohit", "Snehashish", "Akshay"}; /* Using Arrays.asList() method to convert array to ArrayList */ ArrayList<String> studentList= new ArrayList<String>(Arrays.asList(studentNames));
- Using Collections.addAll() method
String studentNames[]={"Mohit", "Rohit", "Snehashish", "Akshay"}; /* Create ArrayList studentList*/ ArrayList studentList= new ArrayList(); /* Using Collections.addAll() method to convert array to ArrayList */ Collections.addAll(studentList, studentNames);
23. How to find the Second Largest Number in the Array in java ?
The below steps can be performed to identify the second largest array element in java
- Intitialize the array with the array elements
- Sort the Array by using Arrays.sort() method
- The last Number is the Array is the largest number after sorting
- Traverse the array elements from 0 to n-2
- compare the array element with the last element in array
package core.java.oracleappshelp.array; import java.util.Arrays; public class SecondLargestNumInArray { public static void main(String[] args) { int studentRollNo[] = new int[] {101,21,45,51,19,2}; // Call Arrays.sort() method Arrays.sort(studentRollNo); // Traverse the StudentRollNo Array till Second last element for(int loop=0; loop < studentRollNo.length; loop++) { // Print second last element if(loop == studentRollNo.length- 2) System.out.println(studentRollNo[loop]); } } }
24. How to validate if a particular value exists in array object in java ?
We can utilise the below array method to get the value from array object
Arrays.asList(<array object>).contains(<array element>);
package core.java.oracleappshelp.array; import java.util.Arrays; public class IsArrayValueExists { public static void main(String args[]) { String[] studentNames = {"Roit", "Mohit", "Vinay", "Mohit", "Akshay" }; System.out.println(isStudentExist(studentNames,"Mohit")); // true System.out.println(isStudentExist(studentNames,"Ajay")); // false } public static boolean isStudentExist(final String[] studentNames, final String value) { return Arrays.asList(studentNames).contains(value); } }
25. Which is legal array initialization – int[] studentId or int studentId[] ?
Both are legal array initialization in java . Preferred one is int[] studentId