ArrayStoreException is a runtime exception which occurs when you try to store non-compatible element in an array object. These type of the elements must be compatible with the type of array object. Say for instance, you can store only string elements in an array of strings. If we try to insert an integer element in an array of strings, we will get ArrayStoreException at runtime.
public class MainClass{
public static void main(String[] args){
Object[] stringArray = new String[5]; // No compile time error : String[] is auto-upcasted to Object[]
stringArray[1] = "JAVA";
stringArray[2] = 100; // No compile time error will occur, but this statement will throw java.lang.ArrayStoreException at runtime
//This is because we are inserting an integer element into an array of string
}
}
The main drawback of the arrays is that arrays are of fixed size. We cannot change the size of an array once it has been created. Therefore, we must know how many elements we want in an array before creating it. You cannot insert or delete the elements once an array has been created. Only the value of the elements can be changed.
Remember that any class that implements an interface must implement the method headings that are declared in that interface. If that particular interface extends from other interfaces, then the implementing class must also implement the methods in the interfaces that are being extended or derived from. As shown in the example above, if we have a class that implements the FourLegs interface, then that class must define the method headings in both the 'FourLegs' interface and the 'Body' interface.Anonymous array is an array without a reference. For example:
public class MainClass{
public static void main(String[] args){
//Creating anonymous arrays
System.out.println(new int[]{1, 2, 3, 4, 5}.length); //Output : 5
System.out.println(new int[]{21, 14, 65, 24, 21}[1]); //Output : 14
}
}
No. We cannot pass a negative integer as an array size. If we do so, there will be no compile time error but NegativeArraySizeException will be prompted at runtime.
public class MainClass{
public static void main(String[] args){
int[] array = new int[-5]; //No compile time error
//but you will get java.lang.NegativeArraySizeException at run time
}
}
No. We cannot change the size of an array once it has been defined. We cannot insert or delete the elements after creating an array. Only the value of the elements can be changed.
Both are the legal methods to declare the arrays in java.
No. We cannot mention the size of an array when we are providing the array contents.
Yes, you can assign array of 100 elements to an array of 10 elements provided they should be of same type. While assigning, compiler only checks the type of the array and not the size.
public class MainClass{
public static void main(String[] args){
int[] a = new int[10];
int[] b = new int[100];
a = b; //Compiler checks only type, not the size
}
}
ARRAY | ARRAYLIST |
---|---|
Arrays are of fixed length. | ArrayList is of variable length. |
You cannot change the size of an array once it has been created. | Size of the ArrayList grows and shrinks as you add or remove the elements. |
Arrays are of fixed length. | ArrayList is of variable length. |
You can use arrays to store both primitive types as well as reference types. | You can store only reference types in an ArrayList. |
You can use Arrays.equals() method to compare one dimensional arrays and to compare multi-dimensional arrays, use Arrays.deepEquals() method.
There are four methods available in java to copy an array.
Using 'for' loop.
Using Arrays.copyOf() method.
Using System.arraycopy() method.
Using clone() method.
ArrayIndexOutOfBoundsException is a runtime exception which occurs when your program tries to access invalid index of an array i.e negative index or index higher than the size of the array.
You can sort the array elements using Arrays.sort() method. This method internally uses quick sort algorithm to sort the array elements.
import java.util.Arrays;
public class MainClass{
public static void main(String[] args){
int[] a = new int[]{45, 12, 78, 34, 89, 21};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
}
}
This is one of the most common java interview question asked to freshers as well as to experienced java professionals of 1 or 2 years. We will discuss couple of methods to find common elements between two arrays.
Using iterative Method: In this method, we iterate both the given arrays and compare each element of one array with elements of other array. If the elements are found to be equal, we will add that element into HashSet. This method also works for those arrays which contain duplicate elements.
Using retainAll() method : This is one of the easiest methods to find the common elements from two arrays. In this method, we create two HashSets using given two arrays and then use reatinAll() method of HashSet to retain only common elements from the two sets.
This is one of the most asked java interview program for freshers. We have discussed two methods of finding duplicates in an array.
Using Brute Force Method :
In this method, we compare each element of an array with other elements. The performance of this method is very low if an array contains lots of elements. Therefore, this method is not recommended in real time.
Using HashSet :
HashSet contains only unique elements. HashSet never allows duplicate elements. We use this property of HashSet to find duplicates in an array. We try to add each element of an array into HashSet using add() method. This method will return true if an element is added successfully otherwise it returns false.
Here is the java program which uses both the methods to find duplicate elements in an array.
dataType[][] arrayRefVar;
dataType [][]arrayRefVar;
dataType arrayRefVar[][];
dataType []arrayRefVar[];
No. You cannot specify an array dimension after an empty dimension while creating multi-dimensional arrays. It gives compile time error.
int[][][] a = new int[][5][]; // Compile time error
int[][][] b = new int[5][][5]; //Compile time error
int[][][] c = new int[][5][5]; // Compile time error
You can search an array to check whether it contains the given element or not using Arrays.binarySearch() method. This method internally uses binary search algorithm to search for an element in an array.
They get default values.
1) Using normal 'for' loop
public class MainClass{
public static void main(String[] args){
int[] a = new int[]{45, 12, 78, 34, 89, 21};
// Iterating over an array using normal for loop
for (int i = 0; i < a.length; i++){
System.out.println(a[i]);
}
}
}
2) Using extended 'for' loop
public class MainClass{
public static void main(String[] args){
int[] a = new int[]{45, 12, 78, 34, 89, 21};
// Iterating over an array using extended for loop
for (int i : a){
System.out.println(i);
}
}
}
This is also one of the java interview program asked many times to java freshers to check the candidate's logical ability and understanding of the language's fundamentals. While writing the program you should not use any sorting methods or any collection types. You should find the second largest number in the given array by iterating the array only once. These are the likely conditions interviewer may ask you to follow.
Given an array of integers, you have to find all pairs of elements in this array such that whose sum must be equal to a given number. For instance if {4, 5, 7, 11, 9, 13, 8, 12} is an array and 20 is the given number, then you have to find all pairs of elements in this array whose sum must be 20. In this example, (9, 11), (7, 13) and (8, 12) are such pairs whose sum is 20.
Given an integer array, you have to separate all zero elements from non-zero elements. You have to move zeroes either to end of the array or bring them to beginning of the array. For example, if {14, 0, 5, 2, 0, 3, 0} is the given array, then moving zeros to end of the array will result {14, 5, 2, 3, 0, 0, 0} and bringing zeroes to front will result {0, 0, 0, 14, 5, 2, 3}. In this post, we will see both as how to move zeros to end and front of an array.
You have been given an integer array and a number. You need to find the continuous sub array of the given array whose sum is equal to given number. For example, If {12, 5, 31, 9, 21, 8} is the given array and 45 is the given number, then you have to find continuous sub array in this array such that whose elements add up to 45. In this case, {5, 31, 9} is such sub array whose elements add up to 45.