2

I am not sure my i am getting NullPointerException exception i am new to java can anybody please help on this.

Code i am using for this -

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;

public class sortNumberOfFile {
    public static void main(String[] args) throws IOException,
            InterruptedException {
        HashSet<String> hs = null;
        String perLine;
        String filename = "C:\\Users\\dummy\\Downloads\\ip.txt";
        BufferedReader br = new BufferedReader(new FileReader(filename));

        while ((perLine = br.readLine()) != null) {
            System.out.println("whole line : " + perLine);

            String[] eachLine = perLine.split(",");
            System.out.println("custom element " + eachLine[0] + " "
                    + eachLine[2] + " count " + eachLine.length);

            for (String str : eachLine) {
                System.out.println("Adding "+str);
                //Thread.sleep(2000);
                hs.add(str);
            }

//          Collections.addAll(hs, eachLine);
            System.out.println(hs);

        }
    }

}

Console Output i am getting -

whole line : 1,2,32,4,5,234,6,12,3,67,3421,123,2,2,34,5,4
custom element 1 32 count 17
Adding 1
Exception in thread "main" java.lang.NullPointerException
    at org.gour.indrajeet.practice.sortNumberOfFile.main(sortNumberOfFile.java:27)
Indrajeet Gour
  • 4,020
  • 5
  • 43
  • 70

2 Answers2

2

NullPointerException is thrown when an application tries to use an object reference, having the null value.

Please note that you have not created a HashSet object yet using new here:

HashSet<String> hs = null;

Also, you are calling a method on a null reference object here:

hs.add(str);

It has to be possibly:

HashSet<String> hs = new HashSet<>();
TryinHard
  • 4,078
  • 3
  • 28
  • 54
2

You first write HashSet<String> hs = null; and later, in your loop hs.add(str);. Since hs is null, you cannot call its add() method.

Instead, declare it like this:

HashSet<String> hs = new HashSet<>();
Hexaholic
  • 3,299
  • 7
  • 30
  • 39