Java MCQ
Java Tricky Arrays Questions
What is the output?
int[] arr = new int[5];
System.out.println(arr[0]);
System.out.println(arr[0]);
In Java, primitive arrays are initialized with default values. For int arrays, all elements are initialized to 0.
What will be printed?
String[] arr = new String[3];
System.out.println(arr[0]);
System.out.println(arr[0]);
For object arrays (like String[]), all elements are initialized to null by default.
What is the output?
int[] arr = {1, 2, 3};
System.out.println(arr[3]);
System.out.println(arr[3]);
Array indices in Java start from 0. For an array of size 3, valid indices are 0, 1, 2. Accessing index 3 throws ArrayIndexOutOfBoundsException.
What will be printed?
int[] a = {1, 2, 3};
int[] b = a;
b[0] = 10;
System.out.println(a[0]);
int[] b = a;
b[0] = 10;
System.out.println(a[0]);
When we assign b = a, both variables reference the same array object. Changing b[0] also changes a[0] because they point to the same memory location.
What is the output?
int[][] arr = new int[2][3];
System.out.println(arr.length);
System.out.println(arr[0].length);
System.out.println(arr.length);
System.out.println(arr[0].length);
3
arr.length gives the number of rows (2). arr[0].length gives the number of columns in the first row (3).
What will be printed?
int[] arr = new int[0];
System.out.println(arr.length);
System.out.println(arr.length);
It's possible to create arrays of size 0 in Java. The length will be 0, and no elements can be accessed.
What is the output?
int[] arr = {1, 2, 3, 4, 5};
for(int i = 0; i <= arr.length; i++) {
System.out.print(arr[i] + " ");
}
for(int i = 0; i <= arr.length; i++) {
System.out.print(arr[i] + " ");
}
The loop runs from i=0 to i=5 (arr.length is 5). When i=5, arr[5] is out of bounds since valid indices are 0-4.
What will be printed?
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
System.out.println(arr1 == arr2);
System.out.println(arr1.equals(arr2));
int[] arr2 = {1, 2, 3};
System.out.println(arr1 == arr2);
System.out.println(arr1.equals(arr2));
false
== compares references (different arrays). Arrays don't override equals(), so it also compares references, not content.
What is the output?
int[][] arr = new int[2][];
arr[0] = new int[3];
arr[1] = new int[4];
System.out.println(arr[0].length);
System.out.println(arr[1].length);
arr[0] = new int[3];
arr[1] = new int[4];
System.out.println(arr[0].length);
System.out.println(arr[1].length);
4
This creates a jagged array where the first row has 3 elements and the second row has 4 elements.
What will be printed?
char[] chars = {'J', 'A', 'V', 'A'};
System.out.println(chars);
System.out.println(chars);
Printing a char array directly converts it to a String. This is a special behavior only for char arrays in Java.