Cannot read the array length because "this.weeklyHours" is null

I am getting a java.lang.NullPointerException error for my calculateTotalPay method and calculateAveragePay method. The error message states that it cannot read the array length because this.weeklyHours is null.

public double calculateAveragePay() {
  double averagePay = 0;
  double totalPay = 0;
 // totalPay = calculateTotalPay();

  averagePay = totalPay / weeklyHours.length;
  return averagePay;

public double calculateTotalPay() {
  int totalAmount = 0;
 // for (int index = 0; index < weeklyHours.length; index++)
    totalAmount += weeklyHours[index];
  return totalAmount;
public class Employee {
    private static final int DEFAULT_WEEKS = 52;
    private String name;
    private double salary;
    private double[] weeklyHours;
    //private int numWeeks;

    public Employee(String name, double salary) { = name;
        this.salary = salary;
        double[] weeklyHours = new double[DEFAULT_WEEKS];

    public Employee(String name, double salary, int numWeeks) { = name;
        this.salary = salary;
        double[] weeklyHours = new double[numWeeks];

>Solution :

From within the Employee class constructor methods, you’re initializing a local variable, as opposed to assigning the class variable.

double[] weeklyHours = new double[DEFAULT_WEEKS];
double[] weeklyHours = new double[numWeeks];

Just remove the declaration type, to access the class variable.

weeklyHours = new double[DEFAULT_WEEKS];
weeklyHours = new double[numWeeks];

Leave a Reply