What is the result of compiling and running the following code?
public class Test{
public static void main(String[] args){
int[] a = new int[0];
System.out.print(a.length);
}
}
public class Test{
public static void main(String[] args){
int[] a = new int[0];
System.out.print(a.length);
}
}
A. 0
B. Compilation error, arrays cannot be initialized to zero size.
C. Compilation error, it is a.length() not a.length
D. None of the above
Answer: Option A
Solution(By Examveda Team)
Step 1:Declare a public class named
Test
.Step 2:
Define the
main
method with the public
and static
modifiers and a parameter of type String
array named args
.Step 3:
Declare an array variable
a
of type int[]
.Step 4:
Initialize the array
a
with a size of 0 using the new
keyword.Step 5:
Print the length of the array
a
using the length
property.Therefore, when you compile and run the code, the output will be:
0
This output corresponds to the length of the array
a
, which is 0.
Join The Discussion
Comments ( 2 )
Related Questions on Array
In Java, arrays are objects of which class?
A. Array
B. Collection
C. ArrayList
D. None of the above
How do you declare a one-dimensional array in Java?
A. int[] myArray;
B. int myArray[];
C. Array
D. All of the above
What is the default initial value of numeric elements in an array of type int in Java?
A. 0
B. 1
C. -1
D. Null
What is the correct way to initialize a two-dimensional array in Java?
A. int[][] myArray = {{1, 2}, {3, 4}};
B. int[2][2] myArray = {{1, 2}, {3, 4}};
C. int[2][2] myArray; myArray[0][0] = 1; myArray[0][1] = 2; myArray[1][0] = 3; myArray[1][1] = 4;
D. None of the above
This should be 1 since it is printing length, not index code.
As we know counting is done from 1 when length is calculated. then why answer is 0.