-1

I am getting this run time error which says there is a null pointer exception. I am just a beginner at Java and don't understand what this means.

Error message is as follows:

Exception in thread "main" java.lang.NullPointerException at MyLongArray.insert(MyLongArray.java:26) at MyLongArray.main(MyLongArray.java:69)

import java.util.*;

public class MyLongArray
{
    private long a[];
    private int nElems;
    
    public MyLongArray(int size)
    {
        
        long[] a = new long[size];
        
        nElems = a.length;
    }
    public int find(long searchKey) {
        int m =0;
        for(int i=0; i < nElems; i++)
            if(searchKey == a[i])
                m = i;
        return m;
    }
    public void insert(long value) {
        @SuppressWarnings("resource")
        Scanner  sc = new Scanner(System.in);
        System.out.print("At what index do you want to insert? "); int i = sc.nextInt();
            a[i] = value;
        
    }
    public long getElem(int index) {
        return a[index];
    }
    public boolean delete(long value) {
        long[] temp = new long[nElems];
        int f = 0;
        int o = 0;
        for(int i=0; i < nElems; i++)
        {
            if(value != a[i])
            {
                temp[o++] = a[i];
            }
            else
                f = 1;
                
        }
        
        for(int j=0; j < nElems; j++)
            a[j] = temp[j];
        
        for(int i=0; i < nElems; i++)
            System.out.print(a[i] + " ");
        
        if (f==1)
            return true;
        else
            return false;
            
    }
    public void display() 
    {
        for(int i =0; i < nElems; i++)
            System.out.print(a[i] + " ");
    }   


     public static void main(String[] args)
    {
        MyLongArray m = new MyLongArray(5);
        m.insert(5);
        m.find(21);
        m.getElem(2);
        m.delete(3);
        m.display();
    
    }
    



}
Mr Duda
  • 1
  • 1

2 Answers2

1

In constructor MyLongArray with long[] a = new long[size], you are declaring new local array a, instead of initializing your class variable array. After that in the insert method, you are trying to set elements in a non-initialized array a.

Use a = new long[size] instead of long[] a = new long[size].

craigcaulfield
  • 3,381
  • 10
  • 32
  • 40
0

You need to use a = new long[size] or this.a = new long[size] to initialize the instance field instead of declaring a local variable a inside the constructor.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80