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.
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.