2

I am storing sum of all pairs of an array element to pairSum[] array. For this I have created PairSum class which store two elements and their sum.

But I am getting null Pointer Exception on line pairSum[k].sum = v

I have created array as

PairSum[] pairSum = new PairSum[val];

What am I doing wrong?

public class test {
            class PairSum{
                int first;
                int second;
                int sum;
            }
            public static void findElements(int arr[], int n){
                int val = (n*(n-1))/2;
                PairSum[] pairSum = new PairSum[val];
                int k=0;
                for(int i=0;i<n-1;i++){
                    for (int j=i+1;j<n;j++){
                        int v = arr[i] + arr[j];
                        System.out.println("sum..." + v);
                        pairSum[k].sum = v;//NullPointerException here
                        System.out.println("valll.." + pairSum[k]);
                        pairSum[k].first = arr[i];
                        pairSum[k++].second = arr[j];

                    }
                }
           }
           public static void main(String[] args) {
                int arr[] = {10, 20, 30, 40, 1, 2};
                int n = arr.length;
                findElements (arr, n);
            }  
          }
js_248
  • 2,032
  • 4
  • 27
  • 38

1 Answers1

2

As of now, you have only created an array that can hold objects of type PairSum. You need to instantiate every PairSum object individually:

pairSum[k] = new PairSum();

Before accessing any PairSum in your pairSum array.

Idos
  • 15,053
  • 14
  • 60
  • 75