简体   繁体   中英

Why the compiler points this “Potential null pointer access” warning?

[JDK/JRE 8, Windows 8.1 64-Bit]

So I have a code somewhat like this:

File file = ...;
BufferedReader reader = ...;
String s;

while ((s = reader.readLine()) != null) {
  s = s.replace("10", "100");

  if (s.startsWith("100100")) {
    ...
  }
}

Until there, everything works fine.

But, if I give any condition to execute the String.replace , for example:

File file = ...;
BufferedReader reader = ...;
String s;

while ((s = reader.readLine()) != null) {
  if (file.getName().startsWith("X_")) {
    s = s.replace("10", "100");
  }

  if (s.startsWith("100100")) {
    ...
  }
}

Then, the compiler gives me a warning Potential null pointer access: The variable s may be null at this location at if (s.startsWith("100100")) { .

Why this happens?

I suspect you're just encountering a limitation of the static analysis used. The warning message does say "Potential". In this case, it's likely because the condition (s = reader.readLine()) != null is rather difficult to propagate fully.

Static analyses like these are often heuristics that may not always do exactly what you expect. They are useful as hint, but they aren't infallible.

You can safely ignore it (provided the code actually works as you intend!), or perhaps add an annotation to suppress that warning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM