0

I am getting null-exception throw error in the following code. What can be the reason for it?

 public static String[] CreateVocab(BufferedReader buffR) throws IOException{
    String[] arr = null;
    int i = 0;
    arr[i]= null;
    String line = new String();
    while((line = buffR.readLine()) != null){
        arr[i] = line;
        i=i+1;
    }
    return arr;     
}

Compiler is showing Null ponter exception in the code arr[i]=null.

1
  • 1
    I see NO reason to downvote this question. And no reason for closeing too. Commented Mar 29, 2012 at 10:07

3 Answers 3

6

This is the cause:

String[] arr = null;
int i = 0;
arr[i]= null; // 'arr' is null

As the number of lines being read is unknown suggest using an ArrayList<String> to store the lines read, and the use ArrayList.toArray() to return a String[] (if returning an ArrayList<String> is not acceptable).

Example that returns a List<String>:

public static List<String> CreateVocab(BufferedReader buffR)
    throws IOException
{
    List<String> arr = new ArrayList<String>();
    String line;
    while((line = buffR.readLine()) != null){
        arr.add(line);
    }
    return arr;     
}

To return an array change return to:

return arr.toArray(new String[]{});
Sign up to request clarification or add additional context in comments.

Comments

3

You haven't created the array - and an array won't solve your problem anyway, because it can't resize. We don't know the number of lines in advance.

Use a collection instead:

public static String[] CreateVocab(BufferedReader buffR) throws IOException{
    List<String> lines = new ArrayList<String>();
    String line = null;
    while((line = buffR.readLine()) != null){
        lines.add(line);
    }
    return lines.toArray(new String[]{});     
}

Comments

1
String[] arr = null; //here you are setting arr to null
int i = 0;
arr[i]= null;        // here you are trying to reference arr

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.