0% found this document useful (0 votes)
772 views

Java Array Interview Questions and Answers

This document contains 29 questions and answers about Java arrays. Some key points covered include: - Arrays are fixed-length data structures that store elements of the same type. They are stored in heap memory. - Arrays can be declared with a size and initialized with data. The default value for primitive types is 0/false and objects is null. - The size of an array cannot be changed after creation. Negative sizes cause exceptions. - Common exceptions include ArrayIndexOutOfBounds and ArrayStore. - Arrays have faster element access than alternatives like ArrayList but are fixed in size.

Uploaded by

Aditya Ingale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
772 views

Java Array Interview Questions and Answers

This document contains 29 questions and answers about Java arrays. Some key points covered include: - Arrays are fixed-length data structures that store elements of the same type. They are stored in heap memory. - Arrays can be declared with a size and initialized with data. The default value for primitive types is 0/false and objects is null. - The size of an array cannot be changed after creation. Negative sizes cause exceptions. - Common exceptions include ArrayIndexOutOfBounds and ArrayStore. - Arrays have faster element access than alternatives like ArrayList but are fixed in size.

Uploaded by

Aditya Ingale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

--------Java Array Interview Questions And Answer------

Q1 What is an Array?
Array is a collection of similar data types. It can not have different data type. It can hold both primitive types (int, float, double)
and object references.
It is fixed in length i.e static in nature.
Arrays are created on the heap memory not on the stack.
Accessing an invalid index of an Array will cause exception.

Q2 How do you declare an Array in java?


You can declare an Array in java by the following way :
dataType[] arrayVariableName = new dataType[arraySize];
for example for int data type, you can declare an int array as :
int[] temp = new int[256]

Q3 What is the default value of Array for different data types?


Data Type Default value
byte, short, int, long 0
float, double 0.0
boolean false
Any object null

Q4 Can you change size of Array in java after creation?


You can not change the size of Array after creation. Although there are other data-structures which can change size after
creation.
Java Array Interview Questions and Answers

Q5 Can you pass the negative number in Array size?


No, you can not pass the negative number as Array size. If you pass a negative number in Array size then you will not get the
compiler error. Instead, you will get the NegativeArraySizeException at run time.

Q6 Can you declare an Array without Array size?


No, you can not declare Array without Array size. You will get compile time error.

Q7 Where does Array stored in JVM memory ?


Array is an object in java. So, Array is stored in heap memory in JVM.

Q8 Given a primitive Array in java, where does in JVM it is stored?


This is a follow-up question of Q7. An Array will always be an object on heap memory, even if the Array is declared to hold
primitive elements.
Q9 What is ArrayStoreException ? When this exception is thrown ?
According to Oracle docs,
ArrayStoreException is a runtime exception. Array must contain the same data type elements.

This exception is thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.
In other words, if you want to store the integer Object in an Array of String you will get ArrayStoreException.

The following code throws ArrayStoreException :


public class JavaHungry {

public static void main(String args[]) {

Object x[] = new String[3];


x[0] = new Integer(0);
}
}

Q10 What is the difference between ArrayStoreException and ArrayOutOfBoundsException ?


ArrayStoreException is thrown if you are trying to add incompatible data type. For example, if you try to add an integer object
to String Array, then ArrayStoreException is thrown.

ArrayOutOfBoundsException is thrown when an attempt is made to access the Array with illegal index. For example, illegal
index means if the index is either negative or greater than or equal to the size of the Array.

Q11 What are the advantages of Array ?


a. We can sort multiple elements of Array at the same time.
b. Using index, we can access the element of the Array in O(1) time.

Q12 What are the disadvantages of Array?


a. To create an Array, contiguous memory is required. It is possible in JVM that the memory is available to accommodate Array
but memory available is not contiguous.

b. The Array is static data structure. It is of fixed size. We can not increase or decrease the size of the Array after creation.

Q13 Can we use Generics with an Array?


No, we can not use generics with an Array.

Q14 What is an Anonymous Array in Java ? Give example?


An array without any name (or reference) is called an Anonymous Array. They are useful for the scenarios where we need one
time usage of Array. For example,

Anonymous int array :


new int[] {2,3,4,5,6,7};

Anonymous String array :


new String[]{"Java", "Hungry"};

Q15 Write a program to print elements of Array ?


public class JavaHungry {

public static void main(String args[]) {

int[] rollNumber = { 23, 17, 20, 29, 30 };


for (int temp : rollNumber)
System.out.print(temp+" ");
}
}

Output :
23 17 20 29 30

Q16 Write a program to sort an Array in Java ?


You do not need to write quick sort or merge sort algorithm in order to sort an Array. You can sort an Array by using
Arrays.sort() method. Check out the program below :

import java.util.*;
public class JavaHungry {

public static void main(String args[]) {

int[] rollNumber = { 23, 17, 20, 29, 30 };


Arrays.sort(rollNumber);
for (int temp : rollNumber)
System.out.print(temp+" ");
}
}

Output :
17 20 23 29 30
Q17 Write a program to check whether two given Arrays are equal, given both contains same data type and same length ?
To check whether two given arrays are equal or not , we can use Arrays.equals() method. Check the program below :

import java.util.*;
public class JavaHungry {

public static void main(String args[]) {

int[] arr1 = {2, 3, 4};


int[] arr2 = {1, 2, 3};

System.out.println(Arrays.equals(arr1 , arr2));

int[] arr3 = {2, 3, 4};

System.out.println(Arrays.equals(arr1 , arr3));
}
}

Output :
false
true

Q18 Which is legal int[] arr or int arr[] ?


Both are legal statements. It is preferred to write int[] arr instead of int arr[].

Q19 Write a program to throw ArrayOutOfBoundsException?


public class JavaHungry {
public static void main(String args[]) {
int[] rollNumber = { 23, 17, 20, 29, 30 };
/* Index below is greater than the size
of the given Array */
int element = rollNumber[6];
for (int temp : rollNumber)
System.out.print(temp+" ");
}
}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at JavaHungry.main(JavaHungry.java:8)
Q20 Write a program to throw ArrayStoreException ?
public class JavaHungry {
public static void main(String args[]) {
Object x[] = new String[3];
x[0] = new Integer(0);
}
}
Output:
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
at JavaHungry.main(JavaHungry.java:6)

Q21 What is the difference between Array and ArrayList ?


Array is static in size i.e of fixed length. Size can not be changed after declaration. ArrayList is dynamic in nature. If you add
elements to an ArrayList, it will automatically increase its size.
Array can contain both primitive and Object data types. ArrayList does not contain primitive data types. It only contains object
entries.
You can find the 8 difference between Array and ArrayList here.

Q22 What is the difference between Array and LinkedList in java ?


Memory required for storing the same number of elements in Array is less as compared to LinkedList. Array only stores the data
of the element whereas LinkedList stores data plus the address of the next node.
Array requires contiguous memory allocation where as LinkedList elements are present all over the heap memory. Unlike Array,
LinkedList does not have limitation of contiguous memory.
You can find more differences between Array and LinkedList here.

Q23 How to find the missing number in a given Array from number 1 to 100 ?
This question is a popular interview question. I have shared the code with explanation here.

Q24 What are jagged arrays in java?


Arrays containing arrays of different length is known as jagged arrays. Multidimensional arrays are also known as jagged arrays.
For example,

Q25 There are two arrays object one containing 100 elements and another containing 50 elements. Both are of same data
type. Can we assign one Array to another Array.
Yes, an Array of 100 elements can be assigned to an Array of 50 elements in java. The only criteria is that both arrays of same
data type. It is because at the time of assigning the values compiler looks for the data type of Array not the size of Array.
import java.util.*;
public class JavaHungry {
public static void main(String args[]) {
int[] arr1 = new int[50];
int[] arr2 = new int[100];
arr1 = arr2;
System.out.println(arr1.length);
}
}
Output :
100

Q26 What are the different ways to copy one Array from another Array?
There are four ways by which we can copy an Array.
a. By using for loop
b. By using clone() method
c. By using Arrays.copyOf() method
d. By using System.arraycopy() method

Q27 Write a program to search a specific element in an Array?


You can use binarySearch(int[], int) method. This method internally uses binary search algorithm.
It is prerequisite for binary search algorithm to have elements sorted. In the given example I have taken an already sorted
Array.
import java.util.*;
public class JavaHungry {
public static void main(String args[]) {
// Sorted Array
int[] arr1 = {1, 2, 3, 4};

/* if element present in Array, binarySearch()


method will return index */
System.out.println(Arrays.binarySearch(arr1, 2));
}
}
Output :
1

Q28 What will happen if you do not initialize an Array?


Array will take default value depending upon the data type.

Q29 How to find duplicate elements in a given Array?


There are many ways by which you can find the duplicates in an Array. I am sharing two ways
a. using for loop and compare
b. using HashSet
import java.util.*;
public class JavaHungry {
public static void main(String args[]) {
String[] arr1 = {"abc", "java", "javahungry", "java", "javahungry" };
for(int i=0; i < arr1.length-1; i++){
for(int j=i+1; j < arr1.length; j++) {
if(arr1[i].equals(arr1[j]) && i!=j ) {
System.out.println("Duplicate in Array is : "+ arr1[j]);

}
}
}
}
}
Output:
Duplicate in Array is : java
Duplicate in Array is : javahungry

Time Complexity O(n^2) i.e quadratic.

HashSet does not allow duplicate elements. You can traverse the array and insert each element into the HashSet. Add elements
using add() method. If it returns true then continue to traverse the array. Otherwise if false then print out the duplicate value.

public class JavaHungry {


public static void main(String args[]) {
String[] arr1 = {"abc", "java", "javahungry", "java", "javahungry" };
HashSet<String> set = new HashSet<String>();
for (String val : arr1)
{
if (set.add(val) == false){
System.out.print (val+" ");
}
}
}
}
Output :
java javahungry
Time Complexity O(n)

Q30 What are the different ways to traverse an Array in java?


a. Using for loop
b. Using for each loop

Q31 Is this a legal way to define arrays int[] arr = new int [4]{1, 2, 3, 4};
This is invalid way to initialize an Array in Java. You can not provide the size of the Array when you are declaring the elements in
it.
Q32 What is two dimensional Array in java?
An Array of an Array in java is called as two dimensional Array.

Q33 How do you declare a two dimensional Array in java?


int[][] arr = new int[4][4];
The above statement will create a 4 x 4 matrix.

Q34 Can we make Array volatile using volatile keyword?


Yes, we can make an Array volatile. Only variable representing an Array can be made volatile.

Q35 Are Array thread-safe ?


Reading an Array is a thread-safe operation but modifications are not.

Q36 What is the time complexity O(n) of different operations of an Array?


a. Access operation : O(1) This means very fast given the index of the element.
b. Search operation : O(n) where n represents the number of elements in an Array.
c. Insertion operation : O(n) where n represents the number of elements in an Array.
b. Deletion operation : O(n) where n represents the number of elements in an Array.

Q37 Given two arrays, find the intersection between them? (solution)
Intersection means common elements. We need to find common elements between two given arrays.
For example :
int[] arr1 = {1, 2, 3, 4, 5, 6};
int[] arr2 = {2, 3, 4, 7, 8};
Output : 2, 3, 4
You can find the code here.

Q38 Find the missing number in an Array between 1 to 100. Given only one number is missing. (solution)
This question is very popular among interviewers. It is one of the simplest question in Array topic.
This question is generally asked during telephonic interview or as a warm up question in face to face round of interviews.
One of the ways to solve this problem is to calculate sum of all numbers from 1 to 100 then subtract it from the sum of all the
numbers in given array. Difference would be the missing number.

Q39 Find out smallest and largest number in a given Array?


Logic to find the smallest and largest number in a given Array is given below :
a. Create two variables for storing largest and smallest number.
b. Initialize smallest variable with value Integer.MAX_VALUE
c. Initialize largest variable with value Integer.MIN_VALUE
d. In each traversal of for loop, we will compare the current element with the largest and smallest number. We will update the
value.
e. If a number is larger than largest, then it can not be smaller than the smallest. So we can skip if first condition is true.
import java.util.*;
public class JavaHungry {
public static void main(String args[]) {
// Given Array
int[] inputArr = {10,43,27,98,75,59,191};
// Setting largest value
int largest = inputArr[0];
// Setting smallest value
int smallest = inputArr[0];
// Iterate through the Given Array
for( int number : inputArr ) {
if(number > largest) {
largest = number;
}
else if (smallest > number) {
smallest = number;
}
}
System.out.println("Largest and Smallest numbers are "
+ largest +" "+smallest);
}
}
Output :
Largest and Smallest numbers are 191 10

Q40 How to reverse an Array in java ? (solution)


You will find this type of questions during telephonic round of interview or early rounds of face to face interview. Make sure
you go through this question before appearing for the interview.

Q41 Write a program to sum all the values of a given Array in java?
public class JavaHungry {
public static void main(String args[]) {
// Given Array
int[] inputArr = {10,43,27,98,75,59,191};
int sum = 0;
//Iterating through the Array
for(int num : inputArr) {
sum = sum + num;
}
System.out.println(sum);
}
}
Output :
503

Q42 How to convert HashSet to Array in java ? (solution)


You can convert HashSet to Array using toArray() method.

Q43 How do you separate zeros and non-zeros in a given Array in java?
Logic to separate zeros and non-zeros is given below :
a. Initialize variable counter to 0.
b. Iterating inputArr from left to right. If inputArr[i] is not zero then assign inputArr[i] to inputArr[counter].
c. Increment the counter by 1.
d. Assign the remaining elements with 0 value.
import java.util.*;
public class JavaHungry {
public static void main(String args[]) {
// Given Array
int[] inputArr = {0,10,43,27,0,98,75,59,191,0};
int counter = 0;
//Iterating through the Array
for(int i=0;i < inputArr.length;i++) {
if(inputArr[i] != 0) {
inputArr[counter] = inputArr[i];
counter++;
}
}
while (counter < inputArr.length) {
inputArr[counter] = 0;
counter++;
}
System.out.println(Arrays.toString(inputArr));
}
}
Output:
[10, 43, 27, 98, 75, 59, 191, 0, 0, 0]

Q44 How to convert Array to ArrayList in java ? (solution)


The easy way to convert Array to ArrayList is using Arrays class asList() method. You need to pass the Array to the asList()
method as argument. For example,
String[] cityNames ={"Boston", "Chicago", "San Francisco", "New York"};
/* One liner - Array to ArrayList conversion*/
ArrayList<String> cityList= new ArrayList<String>
(Arrays.asList(cityNames));
There is another way to convert Array to ArrayList using addAll() method. For details check here.

Q45 How to convert Array to TreeSet in java ? (solution)


To convert Array to TreeSet in java, first we need to convert Array to List using Arrays class asList() method. After converting
Array to List, pass the list object to TreeSet constructor. That's it , Array has been converted to TreeSet. You can confirm by
printing out the values of TreeSet object.

Q46 How to convert ArrayList to String Array in java ? (solution)


There are two ways to convert ArrayList to String Array in java. First method is using ArrayList get() method and second is using
toArray() method. You can check both of the methods here.

Q47 Write a program to find second largest element in a given Array in java?
The easiest way to solve this problem by using sorting. Sort the given Array and then iterate to the second last element.
import java.util.*;
public class LargestSmallest
{
public static void main(String[] args)
{
// Given Array
int inputArray[] = new int[] {10,43,27,98,75,59,191};
// Sort Array
Arrays.sort(inputArray);
// Iterate Array to Second last element
for(int i=0; i < inputArray.length; i++) {
// Print second last element
if(i == inputArray.length- 2)
System.out.println(inputArray[i]);
}
}
}
Output :
98

Q48 How to check if Array contains the desired value or not ?


Suppose we have a String Array temp.
String[] temp = new String[]{"D","H","B","R"};
If desired value exists in the temp Array then below method will return true otherwise false. The below program uses contains()
method to check whether inputArray contains the desired element or not.
import java.util.*;
public class JavaHungry {
public static void main(String args[]) {
String[] inputArray = new String[]{"D","H","B","R"};
System.out.println(isExist(inputArray,"B")); // true
System.out.println(isExist(inputArray,"G")); // false
}
public static boolean isExist(final String[] array, final String obj) {
return Arrays.asList(array).contains(obj);
}
}
Below java program uses equals() method to check whether inputArray contains the desired element.
import java.util.*;
public class JavaHungry {
public static void main(String args[]) {
String[] temp = new String[]{"D","H","B","R"};
System.out.println(isExist(temp,"B")); // true
System.out.println(isExist(temp,"G")); // false
}
public static boolean isExist(final String[] array, final String obj) {
for (String str : array) {
if(str.equals(obj))
return true;
}
return false;
}
}

Q49 Write a program to find the first repeating number in an integer Array?
a. Logic is declare a variable minimum. Iterate through the Array in reverse order i.e from last element to first element. Add
elements to the HashSet one by one.
b. If repeated value occurs then store the index of the repeated value to the minimum variable.
import java.util.*;
public class FirstRepeating {
public static void main(String args[]) {
int[] arr = new int[]{1,2,3,4,5,7,4,9};
firstRepeating(arr);
}
public static void firstRepeating(int[] arr) {
int minimum = -1;
HashSet set = new HashSet();
for (int i = arr.length-1 ;i >=0 ;i--) {
if(set.contains(arr[i]))
minimum = i;
else
set.add(arr[i]);
}
if(minimum != -1){
System.out.println("first repeating element is : "+ arr[minimum]);
}
}
}
Output :
first repeating element is : 4

Q50 Write a program to find the first non-repeating number in an integer Array?
Compare one element with rest of the remaining elements. If value does not match then exit the iteration and print the value.
public class FirstNonRepeating {
public static void main(String args[]) {
int[] arr = new int[]{1,2,3,4,5,1,2,3,5,9};
System.out.println(firstNonRepeating(arr,arr.length));
}
public static int firstNonRepeating(int[] arr, int length) {
int j;
for (int i=0; i < length ;i++) {
for(j=0; j < length ;j++) {
if (arr[i]==arr[j] && i!=j) {
break;
}
}
if (j == length)
return arr[i];
}
return -1;
}
}
Output :
4
------------------------------------------------------------set 2-------------------------------------
1. What is an Array in Java?
An array is a collection of elements (or data) of the same type that are referenced by a common name. For example, we can
store a group of strings, a group of int values, or a group of float values in the array. But, we cannot store some int values or
some float values in the array.

2. How can an array reference variable be declared in java?


Ans: An array can be declared by specifying its data type, name, and size. For example, int[ ] a;
3. What is an array variable?
Ans: An array variable is a reference variable that points to an array object. The memory that is allocated to an array variable
actually stores a reference to an array object. It does not actually store an array itself.

4. Name the keyword that is used for allocating memory space to an array?
Ans: new keyword

5. How to create an array in java?


Ans: We can create an array object by using a new keyword and assign its reference to the variable. The general syntax for the
creation of array object is as follows:
datatype[ ] arrayname = new datatype[size];
For example:
int[ ] myList = new int[10]; // It can store 10 elements of int type.
6. Which element is positioned at num[9] of an array num?
Ans: Tenth element.

7. If, array[ ] = {10, 20, 5, 30, 25};


a) What is array.length?
b) What is array[2]?
Ans: (a) 5, (b) 5

8. How to declare a 2d array of size 2 * 3 to store only characters?


Ans: char[ ][ ] chrs = new char[2][3];

9. How to create an integer array of size 3 * 2 and initialize with values from 1 to 9?
Ans: int[ ][ ] x = {{2, 3}, {3, 5}, {5, 9}};

10. Where are elements of an array stored?


Ans: Elements of an array are stored in the contiguous memory locations of RAM during runtime by JVM. They are stored in
heap memory.

11. What is the total size of an array chrs having 25 elements of char type?
Ans: 50 bytes

12. What is the total size of an array num[100] of int type?


Ans: 400 bytes.
13. What is sorting of array in Java?
Ans: The process of arranging elements of an array in a specified array is called sorting of array.
14. Can we specify array size as negative?
Ans: No, it is not possible to specify array size as negative. Still, if we try to specify the negative size, there will be no compile-
time error, but at runtime, we will get an exception named NegativeArraySizeException.
15. In which of the following lines of code snippets, there will be compile-time error and why?
int[ ][ ] x = new int[2][ ]; // Line 1
int[ ] y = new int[2]; // Line 2
int num = 2; // Line 3
x[1] = y; // Line 4
x[1] = num; // Line 5
Ans: Line 1 will compile fine and it will create two dimensional array.
Line 2 will also compile fine and it will create one dimensional array.
There is no compilation problem in line 3. It declares and initializes an int variable.
Line 4 also compiles fine since a two-dimensional array is an array of arrays. It assigns a one-dimensional array to one of the
dimensions in the two-dimensional array.
Line 5 will create a compilation error problem because we cannot assign an int variable to an int array variable.

16. Can we modify the size (or length) of the array once set it?
Or, can we insert or delete elements after creating an array?
Ans: No. Once the size of an array is defined, we cannot modify it. We cannot add or delete elements after creation of an array.
In other words, an array cannot expand or shrink at runtime.

17. What will happen when the following lines of code are compiled and executed?
int i = -3;
int[ ] arr = new int[i];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
Ans: The code above will compile fine but at runtime, it will throw an exception named NegativeArraySizeException because i is
a negative number that cannot be used as an array index.

18. Will the below code compile and execute successfully?


int i = 3;
int[ ] arr = new int[i];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
Ans: Yes, the lines of code will be compiled successfully but at runtime, there will be ArrayIndexOutOfBoundsException. This
exception occurs when we attempt to use an index that is less than zero or greater than or equal to the length of an array.

19. Will the above lines of code compile and execute successfully? If yes, what will be the output?
public class Test {
public static void main(String[] args)
{
int i = 4;
String[ ] arr = new String[i];
arr[0] = "A";
arr[1] = "B";
arr[2] = "C";
System.out.print(Arrays.toString(arr));
}
}
Ans: Yes, the code will be compiled successfully. The output is [A, B, C, null].

20. Which exception will be thrown at runtime when the below code will be compiled?
public class Test {
public static void main(String[] args)
{
Object[ ] arr = new String[3];
arr[0] = "A";
arr[1] = "B";
arr[2] = 20;
System.out.print(Arrays.toString(arr));
}
}
Ans: The code will compile fine but at runtime, we will get ArrayStoreException (runtime exception). This exception generally
occurs when we attempt to store non-compatible elements in an array object.
The type of the elements must be compatible with the type of array object. For example, we can store only string elements in
an array of type String. If we will attempt to insert integer elements in an array of String, an ArrayStoreException will be thrown
at runtime.

21. For the below code, what will be the total size taken by the whole array in the memory?
double[ ] num = new double[10];
Ans: Each element in the num array is a variable of double type that needs 8 bytes in the memory. So, the whole array will take
space 80 bytes in the memory, plus 8 bytes for the num variable to store the reference of array in the memory.

22. What is the difference between int[ ] arr and int arr[ ]?
Ans: There is no difference between int[ ] arr and int arr[ ]. Both are the legal ways to declare an array in java. int[ ] arr is a
standard declaration.

23. What is an anonymous array in java?


Ans: An array without reference is called an anonymous array. For example:
// Creating an anonymous array.
System.out.print(new int[]{1, 2, 3}.length); // It will display 3.
24. What is the default value of elements of an array at the time of creation?
Ans: When we create an array, it is always initialized with the default values. The default values of an array of different types
are as follows:
If an array is created of byte, short, int, and long type, elements of an array are initialized with 0.0.
If an array is created of float and double type, elements of an array are initialized with 0.
If an array is created of Boolean type, the default value is false.
If an array is created of an Object type, the default value is null.

25. Is there any error in the below code? If not, what is the output of the following program?
import java.util.Arrays;
public class Test {
public static void main(String[] args)
{
String[ ] str = new String[5];
str[0] = "A";
str[1] = "20";
str[3] = "B";
str[4] = "C";
System.out.println(Arrays.toString(str));
}
}
Ans: No, there is no error in the above lines of code. The output will be [A, 20, null, B, C].

26. What is the difference between length() method and length in java?
Ans: The length() method is provided by String class that is used to return the number of characters in the string. For example:
String str = "Hello world";
System.out.println(str.length());
str.length(); will return 11 characters including space.
Whereas, length is an instance variable in arrays that will return the number of values or objects in array. For example:
String[ ] names = {"John", "Herry", "Deepak", "Ivaan", "Ricky"};
System.out.println(names.length);
names.length; will return 5 since the number of values in names array is 5.

27. What is the important difference between an Array and ArrayList in Java?
Ans: There are the following important differences between Arraya and ArrayList in Java. They are as follows:
Array:
Array is static in size. It has a fixed size.
We cannot change the size (or length) of the array after creating it.
An array can contain both primitive data types as well as reference types.
Array in java does not support generics.
Elements of an array can be iterated using for loop.
An Array can be multi-dimensional.
ArrayList:
ArrayList is dynamic in size.
The size of the ArrayList grows or shrinks automatically as we insert or remove elements.
ArrayList cannot contain primitive data types. It contains only objects. That is, we can store only reference types in ArrayList.
ArrayList in java supports generics.
In an ArrayList, we can use an Iterator object to traverse elements.
Arraylist is always of a single dimension.

28. Which one is the preferred collection for storing objects between an Array and ArrayList?
Ans: ArrayList is backed up by array internally. There are several usability advantages of using an ArrayList over an array in Java.
They are:
a) An array has a fixed length at the time of creation. Once it is created we cannot modify its length.
ArrayList is dynamic in size. Once it reaches a threshold, it automatically allots a new array and copies the contents of old array
to the new array.
b) Also, ArrayList supports Generics. But Array does not support Generics.
The array should be used in the place of an ArrayList if
We know the size of an array in advance and do not need re-sizing the collection.
We need to store the same type of elements.

29. Why does not an array support generics in Java?


Or, why cannot we create generic array in java?
Ans: Java does not allow the creation of a generic array because an array carries type information of its elements at runtime.
This information is used at runtime to throw ArrayStoreException if data type of elements does not match with the defined
type of Array.
In the case of Generics, the type information of a collection gets erased at runtime by Type Erasure. Due to which an array
cannot use generics.

30. What are the types of arrays in java?


Ans: Generally, arrays are categorized into two forms that are:
Single dimensional arrays (or 1D array called one-dimensional array)
Multidimensional arrays (or 2D, 3D arrays)

31. What are the main advantages of arrays in java?


Ans: There are several advantages of arrays in Java. They are:
a) The main advantage of array structure is that it organizes data in such a way that it can be easily manipulated.
b) We can access randomly nth element in an array at a constant time.
c) Arrays generally use less space because no variable needs to support navigation.
d) They help to optimize the code, thereby, we can retrieve or sort the data efficiently.

32. What are the drawbacks/disadvantages/limitations of Arrays in Java?


Ans: There are many drawbacks of arrays in java that are as follows:
a) Since arrays in java are fixed in size, we can store only the fixed size of elements in the array.
b) Once the size of an array is created, it cannot be changed. That is, an array cannot expand or shrink at runtime.
c) We cannot store different kinds of elements in an array.

33. What will be the output of the following program?


public class Test {
public static void main(String[] args)
{
int x = 10;
int[ ] nums = new int[x];
x = 30;
System.out.println("x: " +x);
System.out.println("Size of nums: " +nums.length);
}
}
Ans: x: 30, Size of nums: 10

34. What will be the output of the following code?


public class Test {
public static void main(String[] args)
{
int arr[ ] = {1, 2, 3, 4, 5, 6};
for (int i = 1; i < arr.length; i++)
arr[i] = arr[i - 1];
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
}
}
Ans: Output: 1 1 1 1 1 1

35. What is a jagged array in java?


Ans: A two-dimensional array having different rows is called jagged array. It is also called ragged array in java.

36. How many ways of copying an array into another array?


Ans: There are four ways available in java to copy an array into another array. They are:
Using for loop
Using Arrays.copyOf() method
Using System.arraycopy() method
Using clone() method

37. Will the below code compile fine? If yes, what will be the output of the following program?
public class Test {
public static void main(String[] args)
{
int[ ] arr;
arr = new int[1];
arr = new int[2];
arr[0] = 20;
arr[1] = 30;
arr[2] = 40;
}
}
Ans: Yes, the code will compile fine but at runtime, we will get ArrayIndexOutOfBoundsException because once an array is
created, its size cannot be resized.

38. Is there any error in the below code? If not, what will be the output of the following program?
public class Test {
public static void main(String[] args)
{
int[ ] arr = new int[3];
int[ ] arr2 = new int[5];
arr2 = arr;
System.out.println(arr.length);
System.out.println(arr2.length);
}
}
Ans: Output: 3 3

39. Is it possible to mark an array volatile?


Ans: Yes, we can mark an array volatile in Java. But we can make only the reference to array volatile, not the whole array.

40. How can we print elements of an Array in Java?


Ans: Arrays class provides two static methods toString() and deepToString() to print each element of an array.

41. How will we convert an array of String objects into a List?


Ans: Java Arrays class present in java.util package provides a method asList() that accepts an Array as input and returns a List as
output. The sample code is as follows:
String[ ] myArray = {"George" , "Jack" , "Ryan"};
List<String> myList = Arrays.asList(myArray);
System.out.println(myList);
Output: [George, Jack, Ryan]

42. Which new methods were introduced in Java 8 for the processing of Arrays on multi-core machines?
Ans: Java 8 has enhanced the Arrays class by introducing some new methods that can run efficiently on multi-core machines.
These methods start with keyword parallel.
For example, Arrays.parallelSetAll(), Arrays.parallelSort(), etc. These methods process Arrays in parallel to make Java code very
fast on a multi-core machine.

43. Suppose there are two array objects of int type. one has 20 elements and another one has 10 elements. Is it possible to
assign an array of 20 elements to an array of 10 elements?
Ans: Yes, it is possible to assign an array of 20 elements to an array of 10 elements provided they should be of the same type.
Java compiler checks only the type of the array, not the size while assigning. The sample code is as follows:
int[ ] x = new int[10];
int[ ] y = new int[20];
x = y; // Here, array references x and y both are pointing to the same array contents (i.e. array of 20 elements).

44. Identify and fix errors in the below code. What will be output after fixing them?
import java.util.Arrays;
public class Test {
public static void main(String[] args)
{
int num[ ] = new int[6]{1, 2, 3, 4, 5, 6};
System.out.println(Arrays.toString(num));
}
}
Ans: We need not define the size of the array when we are storing the array contents. After removing the size of array, the
output is [1, 2, 3, 4, 5, 6]

45. Can we check the equality of two arrays in java?


Or, how will you compare the two arrays in java?
Ans: Yes, we can compare the equality of two arrays in java. Arrays class provides two methods: Arrays.equals() method to
compare one-dimensional array and Arrays.deepEquals() for comparing multidimensional arrays. The sample code is as:
String[ ] s1 = {"Ivaan", "John", "Helly", "Ricky"};
String[ ] s2 = {"Deep", "Shubh", "Herry", "Micky"};
String[ ] s3 = {"Ivaan", "John", "Helly", "Ricky"};
System.out.println(Arrays.equals(s1, s2)); // Output : false
System.out.println(Arrays.equals(s1, s3)); // Output : true

46. How will you sort an array of objects?


Ans: To sort an array of objects, use Arrays.sort() method. This method internally uses quick sort algorithm to sort an array of
objects. The sample code is as follows:
String[] s1 = {"Ivaan", "John", "Helly", "Ricky"};
Arrays.sort(s1);
System.out.println(Arrays.toString(s1));
Output: [Helly, Ivaan, John, Ricky]
If you want to sort a list of objects, use Collections.sort() method. Collections internally use the Arrays sorting method. So, both
of them have the same performance except that Collections take some time to convert list to an array.
47. Can we check an array contains a particular element or not?
Ans: Arrays class provides two methods: isExists() and contains() to check an array has an element or not. Both the methods
return true if an array has elements, otherwise returns false. The sample code is as:
String[ ] s1 = {"Ivaan", "John", "Helly", "Ricky"};
List<String> nameList = new ArrayList<>(Arrays.asList(s1));
System.out.println(nameList.contains("John")); // true.

48. Can we retrieve the class name of an array?


Ans: Yes, we can retrieve the class name of an array using getClass() and getName() methods. The getClass() method of the
Object class returns the runtime class of the object.
While the getName() method of the Class class returns the name of the class/array class. The sample code is as:
String[] s1 = {"Ivaan", "John", "Helly", "Ricky"};
System.out.println(s1.getClass().getName()); // Output: java.lang.String;

49. Which method of the Arrays class can be used to search/find a particular element in an array?
Ans: The Arrays.binarySearch() method can be used to search/find a particular element in an array. This method uses the binary
search algorithm.
The array should be in natural ordering (either in ascending or descending order) before calling it. This is the simplest and most
efficient approach to find an element in a sorted array.

50. What is the difference between linear search and binary search in java?
Ans: Binary search is much faster than linear search for a large array. Binary search algorithm is mostly used for large size array
whereas, linear search is used for very small size array.

51. Which kind of operations can be performed on an array?


Ans: There are several operations that can be performed on array. They are:
Searching
Sorting
Traversal
Deletion
Insertion

52. What are the simple approaches to find duplicate elements in an array?
Ans: There are mainly three simple approaches to find duplicate elements from an array.
a) Brute Force Method: In this approach, each element of an array is compared with elements of another array. If any two
elements are found equivalent, we consider them as duplicates. The time complexity of this approach is O(n^2).
b) Using HashSet: In this approach, we use the HashSet class to find the duplicate elements in an array. To find the duplicate
elements, first iterate over the array elements and then add them into HashSet by calling add() method of the HashSet class.
If the method returns false it means that the element is already present in the Set. It takes O(n) time to find the duplicate
elements.
c) Using HashMap: We can also use HashMap to find duplicate elements in an array. HashMap uses key-value pair to store an
element.
To find the duplicate array element, we store elements of the array as keys and their occurrence as values. If the value of any
key is greater than 1, the key is considered a duplicate element. Its time and space complexity is O(n).

53. Which of the following are valid declarations?


a. String[ ] green = new String[ ] {"green"};
b. String[ ] red = new String[1] {"red"};
c. String bear [ ] = new String[ ] {};
d. String[ ] obj = new String[ ] {};
Ans: a, c, d, are valid declarations.

54. Which of the following are valid declarations of array?


a. String[ ][ ][ ] a = new String[ ][2][ ];
b. int[ ][ ][ ] b = new int[3][3][ ];
c. float[ ][ ][ ] c = new float[3][ ][5];
d. Object[ ][ ] obj = new Object[1][ ];
Ans: b and d are valid declarations of arrays because while creating the multidimensional arrays, we cannot specify an array
dimension after an empty dimension. It generates compile-time error.

55. Identify and fix the error in the following lines of code.
int x;
int[ ] num = {2, 4, 6, x, 10};
Ans: There is an error in the first line of code because the variable x is not initialized.

You might also like