Java - What is the output: array length access?

Question

What is the output of the following code?

int[] salary;
int len = salary.length;


Click to view the answer

// A runtime error. salary is not referring to any array object yet.
int len = salary.length;

Note

length is the property of the array object you create.

Until you create the array object, you cannot use its length property.

Demo

public class Main {
  public static void main(String[] args) {
    int[] salary;
    // int len = salary.length;
    // Create an int array of length 1000 and assign its reference to salary
    salary = new int[1000];

    // Correct. len has a value 1000
    int len = salary.length;
    System.out.println(len);// w w  w.  ja va  2s.c om
  }
}

Result

Related Quiz