Java Arrays Interview Questions
-
Array Initialization:
Question: Explain the different ways to initialize an array in Java.
Answer: Arrays in Java can be initialized using the new keyword, by specifying the size along with the declaration, or by directly assigning values in curly braces. For example:
int[] array1 = new int[5]; int[] array2 = {1, 2, 3, 4, 5}; -
Multidimensional Arrays:
Question: How do you declare and initialize a two-dimensional array in Java?
Answer: A two-dimensional array can be declared and initialized using the following syntax:
int[][] twoDArray = new int[3][4];This creates a 3x4 matrix of integers.
-
Array Length:
Question: How do you find the length of an array in Java?
Answer: The length of an array in Java can be obtained using the
lengthproperty. For example:int[] numbers = {10, 20, 30, 40, 50}; int arrayLength = numbers.length; // arrayLength will be 5 -
Array Copy:
Question: Discuss different methods to copy an array in Java.
Answer: Arrays in Java can be copied using methods such as
System.arraycopy(), theclone()method, or usingArrays.copyOf(). Each method has its own advantages and use cases. -
Enhanced For Loop:
Question: What is the enhanced for loop (for-each loop) in Java, and how is it used with arrays?
Answer: The enhanced for loop simplifies iteration over arrays. For example:
int[] numbers = {1, 2, 3, 4, 5}; for (int num : numbers) { System.out.println(num); } -
Arrays Class:
Question: How can the
java.util.Arraysclass be used with arrays in Java?Answer: The
Arraysclass provides utility methods for working with arrays, such as sorting, searching, and converting arrays to lists. For example:int[] numbers = {5, 2, 8, 1, 3}; Arrays.sort(numbers); -
Jagged Arrays:
Question: What is a jagged array in Java?
Answer: A jagged array is an array of arrays where each element can be an array of different sizes. For example:
int[][] jaggedArray = { {1, 2, 3}, {4, 5}, {6, 7, 8, 9} };
No comments:
Post a Comment