-2
import java.util.Scanner;

public class Java3{
    int sumAll = 0;
    int sumFive = 0;
    int sumLast = 0;
    int arr[];
    int n;
    
    void arraySum(int[] arr) {
        for (int i = 0; i < arr.length; ++i) {
            sumAll += arr[i];
            if (i == 4)
                sumFive += sumAll;
            if (i >= (arr.length - 5))
                sumLast += arr[i];
        }
        System.out.println("sum all  = " + sumAll 
            + " sum first five " + sumFive 
            + " sum last five " + sumLast);
    }

    public static void main(String [] args) {
        Java3 obj1 = new Java3();
        Scanner scan1 = new Scanner(System.in);
        System.out.println("enter the number of elements");
        obj1.n = scan1.nextInt();
        System.out.println("enter the elements");
        for (int i = 0; i < obj1.n; ++i)
            obj1.arr[i] = scan1.nextInt();
        obj1.arraySum(obj1.arr); 
    }
}

The error I get

java.lang.NullPointerException

Errors on Null pointer exception has been asked and answered several times before, but I do not understand those explanations. Can anyone please explain it in a very easy manner. This is my code, and it is showing me the error at runtime. This code is supposed accepts the size of an integer array followed by the integer array. Then calls a function which calculates:

  1. sum of all digits
  2. sum of first 5 digits
  3. sum of last 5 digits

and prints each value in the console..

vsminkov
  • 10,912
  • 2
  • 38
  • 50

3 Answers3

2

Seems like you are a beginner in coding, nullPointerException occurs whenever you are trying to access the value of an object that is not defined. In your case you did not define your array. You should have defined your array as given below before trying to add values into the array this will remove the exception.

obj1.arr = new int[obj1.n];

Doing this will define your array in your object and with obj1.n it will initialize its size. Hope you can proceed from here. Please refer the usage of new and constructors in java.

Manesh
  • 586
  • 3
  • 14
  • 31
1

The problem was you took the length of array as input , but you did not initialize the array . Please add this one line in the code:

obj1.n = scan1.nextInt();
obj1.arr = new int[obj1.n];
Harmandeep Singh Kalsi
  • 3,315
  • 2
  • 14
  • 26
1

You should define your arr size. until you define the arr size it is null, and there is no memory will be allocated. You can avoid this by using ArrayList instead of array or define your arr with sum big number of size and asker user to enter the number of values less than that size.

int arr[] = new int[100];

define the array size once you know the value

obj1.arr = new int[obj1.n+1];

Nagaraju Badaeni
  • 890
  • 8
  • 14