Shahin
Shahin

Reputation: 27

Findbugs Possible null pointer dereference in java

I am using FindBugs to detect bugs that the code contains. I have found some solutions to some bugs, however, I can not understand why it still shows the "Possible null pointer dereference" bug in the line of checking "micro". In the while loop, I have shown that my input should be different from null value, however, it still shows that bug exists. If possible could you tell how to fix this, please ? Thanks in advance! The code is below:

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;


public class FindBug {

    public static void main(String args[]) 

    {


        InputStreamReader reader = new InputStreamReader(System.in,Charset.defaultCharset());
        BufferedReader bufferedreader = new BufferedReader(reader);

        String scan = null;

        boolean nextfound=false;

        try 
        {
           while(null!=(scan= bufferedreader.readLine())&&nextfound)

            {
              scan=scan.replace('i', 'a');

            }
        } 
        catch (IOException ioex) 
        {
            System.err.println(ioex.getMessage());
        }

        if (scan.equals("micro")) 
        {
            System.out.println("The result is macro!");
        } 


        else

        {
            System.out.println("Something else!");
        }
    }
}

Upvotes: 0

Views: 2933

Answers (2)

Dams
Dams

Reputation: 997

scan could be null and perhaps you can simply invert your test

if ("micro".equals(scan){
   System.out.println("The result is Macro!")
}

and there are also some mistakes :

scan=scan.replace('i', 'a'); will never be executed because nextfound is always false

while(null!=(scan= bufferedreader.readLine())&&nextfound)
{
    scan=scan.replace('i', 'a');
}

bufferReader is never closed you should add finally block in your code

...
catch (IOException ioex) {
    System.err.println(ioex.getMessage());
} finally {
    try {
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Upvotes: 4

Joe C
Joe C

Reputation: 15684

If your input is empty, then your while loop will not execute. scan will be set to null, and voila, NullPointerException.

Upvotes: 0

Related Questions