-4

Why am I getting Error at run time when b.initialize() from main is called?

The problem is in the initialize() code.

I am getting NullPointerException when giving input for second line.

Exception in thread "main" java.lang.NullPointerException
        at Bubble.initialize(Bubble.java:17)
        at Bubble.main(Bubble.java:46)

import java.io.*;
public class Bubble {

    private int size;
    private int[] arr;
    public Bubble(int N)
    {
        size = N;
    }
    public void initialize()
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        for(int i=0; i<size; i++)
        {
          try {
                this.arr[i]=Integer.parseInt(br.readLine());
            }
            catch(IOException ioe){}
        }
    }
    public int[] sort()
    {
        int max=size-1;
        int temp=0;
        while(max==0)
        {
            for(int i=0;i<max;i++)
            {
               if(arr[i]>arr[i+1])
               {
                   temp = arr[i+1];
                   arr[i+1]=arr[i];
                   arr[i]=temp;
               }

            }
        max--;
      }
      return arr;
    }

    public static void main(String[] args)
    {
        Bubble b = new Bubble(5);
        b.initialize();
        int res[] = b.sort();
        for( int el : res )
        System.out.println(el);
    }
}

Thanks in advance ! Abhishek

Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59
Abhishek Saxena
  • 292
  • 3
  • 15
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Jeroen Vannevel Jul 22 '14 at 10:49

1 Answers1

1

You never initialize your arr array. Just add it to your constructor:

public Bubble(final int size) {
    this.size = size;
    this.arr = new int[size];
}

Also note that I renamed the N parameter. Variables in Java should start with a lower case letter.

Keppil
  • 45,603
  • 8
  • 97
  • 119
  • @Abhishek: You are very welcome. Don't forget to mark an answer as accepted if you feel that your question got answered properly. – Keppil Jul 22 '14 at 11:09