Array Interview Questions:-
1. What is ArrayStoreException in java? When you will get this exception?
ArrayStoreException is a run time exception which occurs when you try to store non-compatible element in an array object. The type of the elements must be compatible with the type of array object.
For example :- you can store only string elements in an array of strings. if you try to insert integer element in an array of strings, you will get ArrayStoreException at run time.
2. How to check if array contains a duplicate number?
Here are few ways we can check if an array has duplicates or not :-
1. brute force method :- Which compares each element of Array to all other elements and returns true if it founds duplicates. Though this is not an efficient choice it is the one which first comes to mind.
2. Another quick way of checking if a Java array contains duplicates or not is to convert that array into Set. Since Set doesn’t allow duplicates size of the corresponding Set will be smaller than original Array if Array contains duplicates otherwise the size of both Array and Set will be same.
3. One more way to detect duplication in java array is adding every element of the array into HashSet which is a Set implementation. Since the add(Object obj) method of Set returns false if Set already contains an element to be added, it can be used to find out if the array contains duplicates in Java or not.
3. What are the difference between Array and Linked List data structure?
There are several differences between Array and Linked List :-
1. Array needs contiguous memory allocation which may result in java.lang.OutOfMemoryError: Java Heap Space if there is not enough contiguous ( a big chunk) of memory in Java Heap.On the other hand, Linked List is distributed data structure, it's element are scattered over heap and doesn't need a contiguous memory allocation. This makes linked list ideal, if you have scattered memory.
2. Fixed Length :- array is a fixed length data structure, you provide length or size of array at the time of creation, later you can not modify that size.
Linked List is dynamic data structure, it can grow and doesn't required size to be specified at the time of creation, because each node keep tracks of other.
3. It is easy to insert and delete elements from Linked List than array, especially inserting element at beginning of linked list, and deleting element from end of linked list is O(1) operation.Array is fixed length data structure, so memory is allocated during initialization, and doesn't really change due to addition and removal of elements. Though you can set a particular index null, to cut the reference count of that object.
Array is ideal for implementing fast caches e.g. HashMap or Hashtable, which requires constant time retrieval e.g. Map data structure provides O(1) performance for get(Key key) operation. While Linked List based structure provides liner performance i.e. O(n) for retrieval operation, where n is the number of elements in linked list.
4. Array can be one or multi-dimensional. Two dimensional array are most common in multi-dimensional and used to represent matrix in Java. You can use two dimensional array to represent a plain of x,y coordinates, frequently used in Game programming. Java programming language provides support for creating array at syntax level, it supports both single and multidimensional array.
Linked List can be singly, doubly or circular linked list. Java API also provides a class called java.util.LinkedList, which is an implementation of doubly linked list data structure.
4. What is the advantage of an array over individual variables ?
When storing multiple related data, it is a good idea to use arrays. This is because arrays are named using only 1 word followed by an element number.
For Example :-
To store the 10 test results of 1 student, one can use 10 different variable names (grade1,grade2,grade3,grade4.....grade10). With arrays only 1 name is used, the rest are accessible through the index name(grade,grade,grade,grade.........grade).
5. How do you access the values within an array?
Arrays contain a number of elements, depending on the size you gave it during variable declaration. Each element is assigned a number from 0 to number elements-1. To assign or retrieve the value of a particular element, refer to the element number.
For Example :-
If you have a declaration that says "intscores;", then you have 5 accessible elements, namely scores,scores,scores,scores,scores.
6. What are the difference between Array and ArrayList in Java?
There are several difference Array and ArrayList :-
1. Array is a fixed length data structure. You can not change length of Array once created in Java.
ArrayList is a variable length Collection class. ArrayList re-size itself when gets full depending upon capacity and load factor. Since ArrayList is internally backed by Array in Java, any resize operation in ArrayList will slow down performance as it involves creating new Array and copying content from old array to new array.
2. You can not use Generics along with Array, as Array instance knows about what kind of type it can hold and throws ArrayStoreException, if you try to store type which is not convertible into type of Array.
ArrayList allows you to use Generics to ensure type-safety.
3. To calculate length of array. Array provides length variable which denotes length of Array.
ArrayList provides size() method to calculate size of ArrayList in Java.
4. Array can contain both primitives and Objects in Java.
You can not store primitives in ArrayList, it can only contain Objects. Autoboxing of Java 5 may give you an impression of storing primitives in ArrayList, it actually automatically converts primitives to Object.
5. You can create instance of ArrayList without specifying size, Java will create Array List with default size but its mandatory to provide size of Array while creating either directly or indirectly by initializing Array while creating it. By the way you can also initialize ArrayList while creating it.
7. How to sort Array in descending order?
You can even use Collections.reverseOrder() if you want to sort array in the decreasing order, which returns a reverse Comparator to sort objects in the order opposite of their natural ordering defined by the compareTo() method. For a primitive array, there is no direct way to sort in descending order. The Arrays.sort() method which is used to sort a primitive array in Java doesn't accept a boolean to sort the primitive array in reverse order.
You might have seen the error "no suitable method found for sort(int,comparator<object>)" which occurs when programmers try to call the Arrays.sort() method by passing reverse Comparator defined by Collection.reverseOrder().
8. How to Add Elements of two Arrays in Java?
Java doesn't support operator overloading. You cannot use the plus operator to add two arrays in Java e.g. if you have two int arrays a1 and a2, doing a3 = a1 + a2 will give compile time error. The only way to add two arrays in Java is to iterate over them and add individual elements and store them into a new array.
This is also not easy because the array can be of different length, so you need to make some rules and apply them to your method e.g. you can throw IllegalArgumentException if you get two arrays which are not of the same type and their length is different.
9. What is the Jagged Arrays In Java?
Jagged arrays in java are arrays containing arrays of different length. Jagged arrays are also multidimensional arrays. Jagged arrays in java sometimes are also called as ragged arrays.
10. What is the java.util.Arrays Class In Java?
This class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists. The methods in this class all throw a NullPointerException, if the specified array reference is null, except where noted.
This class is a member of the Java Collections Framework.
Let's discuss some of the useful methods of Arrays Class in java.
This means you can get any supported look and feel on any platform. The disadvantage of lightweight components is slower execution. The advantage is uniform behavior on all platforms.
11. What is difference between ArrayIndexOutfOBounds and ArrayStoreException?
There are major differences between ArrayIndexOutfOBounds and ArrayStoreException :-
ArrayIndexOutOfBoundsException :- ArrayIndexOutOfBoundsException comes when your code tries to access an invalid index for a given array e.g. negative index or higher index than length - 1.public class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
ArrayStoreException :- ArrayStoreException comes when you have stored an element of type other than type of array. public class ArrayStoreException extends RuntimeException
Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.
12. Difference between a and a in Java?
You can declare an array in Java by either prefixing or suffixing with 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,
int a, b; // first is int array, second is just int variable
int c, d; // both c and d are integer array
13. What is volatile variable in Java?
Volatile keyword is used to make any variable volatile in Java environment. The volatile keyword can only be applied to a variable, it can not be applied to class or method. using volatile keyword along with class and method is a compiler error. A volatile is also referred as modifier in Java.
Any variable which is shared between multiple threads should be made variable, in order to ensure that all thread must see the latest value of the volatile variable.
A signal to compiler and JIT to ensure that compiler does not change ordering or volatile variable and moves them out of synchronized context. You want to save the cost of synchronization as volatile variables are less expensive than synchronization.
14. How to sort an array in Java?
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 array in custom order.
15. What is the difference between a Vector and an Array. Discuss the advantages and disadvantages of both?
Differences between a Vector and an Array :-
(a). A Vector is a dynamic array, whose size can be increased, where as an Array size can not be changed.
(b). A Vector is a class where as an Array is not.
(c). Reserve space can be given for Vector, where as for Arrays can not.
(d). Vectors can store any type of objects, where as an Array can store only homogeneous values.
Advantages of Arrays :-
(a). It is easy to sort an array.
They are more appropriate for storing fixed number of elements.
Arrays supports efficient random access to the members.
Disadvantages of Arrays :-
(a). Dynamic creation of arrays is not possible.
(b). Multiple data types can not be stored.
(c). Elements can not be deleted
Advantages of Vector :-
(a). Multiple objects can be stored.
(b). Elements can be deleted from a vector.
(c). Size of the vector can be changed.
Disadvantages of Vector :-
(a). A vector is an object, memory consumption is more.
16. What is the difference between standard Java Array and Arraylist class?
(a). Standard Java Arrays are fixed length once they are created.
(b). Arraylist supports dynamic arrays that can grow depending on demand.
17.What is the default values of all the elements of an array defined as an instance variable?
If the array is an array of primitive types, then all the elements of the array will be initialized to the default value corresponding to that primitive type whereas if the array is an array of references (of any type), all the elements will be initialized to null.. e.g. All the elements of an array of int will be initialized to 0, while that of Boolean type will be initialized to false.
18. What are the difference between ArrayList and LinkedList in Java ?
Difference between ArrayList and LinkedList in Java :-
(1). Implementation :- ArrayList is the resizable array implementation of list interface , while LinkedList is the Doubly-linked list implementation of the list interface.
(2). Performance :- Performance of ArrayList and LinkedList depends on the type of operation
(a). get(int index) or search operation :- ArrayList get(int index) operation runs in constant time i.e O(1) while LinkedList get(int index) operation run time is O(n) .
The reason behind ArrayList being faster than LinkedList is that ArrayList uses index based system for its elements as it internally uses array data structure , on the other hand ,
LinkedList does not provide index based access for its elements as it iterates either from the beginning or end (whichever is closer) to retrieve the node at the specified element index.
(b). insert() or add(Object) operation :- Insertions in LinkedList are generally fast as compare to ArrayList.
In LinkedList adding or insertion is O(1) operation . While in ArrayList, if array is full i.e worst case, there is extra cost of resizing array and copying elements to the new array , which makes runtime of add operation in ArrayList O(n) , otherwise it is O(1) .
(c). remove(int) operation :- Remove operation in LinkedList is generally same as ArrayList i.e. O(n).
In LinkedList , there are two overloaded remove methods. one is remove() without any parameter which removes the head of the list and runs in constant time O(1) .
The other overloaded remove method in LinkedList is remove(int) or remove(Object) which removes the Object or int passed as parameter . This method traverses the LinkedList until it found the Object and unlink it from the original list . Hence this method run time is O(n).
While in ArrayList remove(int) method involves copying elements from old array to new updated array , hence its run time is O(n).
3. Reverse Iterator :- LinkedList can be iterated in reverse direction using descendingIterator() while there is no descendingIterator() in ArrayList , so we need to write our own code to iterate over the ArrayList in reverse direction.
4. Initial Capacity :- If the constructor is not overloaded , then ArrayList creates an empty list of initial capacity 10 , while LinkedList only constructs the empty list without any initial capacity.
5. Memory Overhead :- Memory overhead in LinkedList is more as compared to ArrayList as node in LinkedList needs to maintain the addresses of next and previous node. While in ArrayList each index only holds the actual object(data).
19.What is synchronize ArrayList in java?
ArrayList is non-synchronized and should not be used in multi-thread environment without explicit synchronization.
There are two ways to synchronize explicitly :-
(a). Using Collections.synchronizedList() method
(b).Using thread-safe variant of ArrayList: CopyOnWriteArrayList
20. How to serialize ArrayList in java?
ArrayList is serializable by default. This means you need not to implement Serializable interface explicitly in order to serialize an ArrayList. In this tutorial we will learn how to serialize and de-serialize an ArrayList.
21. If we don't provide any arguments on the command line,will the String array of Main method be empty or null?
The String array of the main() method will remain empty but not null.