Welcome to the Java Array Coding Quiz. In this quiz, we present 10 coding MCQ questions to test your coding knowledge on the Java Array topic. Each question has a correct and brief explanation.
1. What is the output of the following Java code snippet?
int[] array = {1, 2, 3, 4, 5};
System.out.println(array[2]);
Answer:
Explanation:
Arrays in Java are zero-indexed. array[2] refers to the third element in the array, which is 3.
2. What does this Java code snippet output?
int[] numbers = new int[5];
System.out.println(numbers[3]);
Answer:
Explanation:
In Java, integer arrays are initialized with default values of 0 for each element. numbers[3] refers to the fourth element, which is 0.
3. Identify the output of the following code:
int[] nums = {1, 2, 3, 4, 5};
for (int i = 0; i < nums.length; i++) {
nums[i] = nums[i] * 2;
}
System.out.println(nums[2]);
Answer:
Explanation:
The loop doubles each element of the array. So, nums[2], which was initially 3, becomes 6.
4. What will be printed by this Java code?
int[] array = new int[]{1, 2, 3, 4, 5};
System.out.println(array[array.length - 1]);
Answer:
Explanation:
array.length is 5, so array[array.length - 1] is array[4], which is the last element of the array, 5.
5. What does this code snippet output?
int[][] matrix = {{1, 2}, {3, 4}, {5, 6}};
System.out.println(matrix[1][1]);
Answer:
Explanation:
matrix[1][1] accesses the second element of the second array, which is 4.
6. What is the result of executing this code?
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[numbers.length]);
Answer:
Explanation:
Accessing numbers[numbers.length] attempts to access an index outside the bounds of the array, resulting in an ArrayIndexOutOfBoundsException.
7. What will the following Java code snippet output?
int[] array = {1, 2, 3, 4, 5};
int[] anotherArray = array;
anotherArray[0] = 10;
System.out.println(array[0]);
Answer:
Explanation:
anotherArray is a reference to the same array as the array. Changing an element via anotherArray will affect the array as well.
8. What does the following code snippet print?
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int number : numbers) {
sum += number;
}
System.out.println(sum);
Answer:
Explanation:
This code calculates the sum of all elements in the array, which is 15.
9. Determine the output of this Java code:
int[] values = new int[3];
values[0] = 10;
values[1] = 20;
System.out.println(values[2]);
Answer:
Explanation:
The array is initialized with default integer values (0). Since values[2] is not explicitly set, it remains 0.
10. What is the result of the following code snippet?
int[] arr = {1, 2, 3, 4, 5};
int x = arr[1] + arr[4];
System.out.println(x);
Answer:
Explanation:
arr[1] is 2 and arr[4] is 5. Their sum, 2 + 5, is 7.
Comments
Post a Comment
Leave Comment