0

I wrote a small program to read a csv file...I used buffered reader for that... My code looks like this:

package files;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import bk.bk;

public class QwithLinkedList{
    public static void main(String args[]) throws Exception{
        FileReader f=new FileReader("G:/bk.csv");
        BufferedReader br=new BufferedReader(f);
        String line;
        while((line=br.readLine())!=(null)){
            System.out.println(line);
        }
    }
}

Above is perfect code but my question is that I'm getting an exception with this code :

package files;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import bk.bk;

public class QwithLinkedList{
    public static void main(String args[]) throws Exception{
        FileReader f=new FileReader("G:/bk.csv");
        BufferedReader br=new BufferedReader(f);
        String line;
        while(!(line=br.readLine()).equals(null)){
            System.out.println(line);
        }
    }
}

The output for the above code is this :

a1
bk
abc
def
ghi
jkl
bharath
Exception in thread "main" java.lang.NullPointerException
    at files.QwithLinkedList.main(QwithLinkedList.java:14)

Someone please explain why it is giving an exception with the above code. Moreover if(a!=b) and !a.equals(b) are't they same ?

Bharat
  • 1,044
  • 15
  • 34
  • 3
    Because you end up with `null.equals(...)` but `null` doesn't have any methods, including `equals`. – Pshemo Mar 15 '17 at 10:04
  • `a != b` and `!a.equals(b)` are _not_ the same. The first compares _object identity_ whereas the second simply invokes the (possibly overridden) [`public boolean equals(Object obj)`](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#equals-java.lang.Object-) on the `a` instance. – jensgram Mar 15 '17 at 10:08
  • @bharath: The difference between `==` and `equals()` (or `!=`and `!equals()`) is vital for java programming. Please make sure you understand the difference and what @jensgram writes, otherwise you'll run into very hard to find bugs. – sruetti Mar 15 '17 at 10:14
  • @pshemo thanks man...now I got to know the difference – Bharat Mar 15 '17 at 10:24

2 Answers2

0

When checking for null, always use == or !=. Using equals will always become a NullPointerException if what you are checking is null.

The difference between == and equals is that the former checks whether or not both sides points to the same address in memory, while the latter checks for object equality.

Tobb
  • 11,850
  • 6
  • 52
  • 77
0

When checking for a null value, never use the .equals() since it might return a NullPointerException as in your case.

JonasJR
  • 76
  • 9
  • 1
    You just confirmed OP problem but didn't explain its cause. Question is "**why** it is giving an exception with the above code" (emphasis mine) – Pshemo Mar 15 '17 at 10:16