Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange Java compiler warning: incorrect "potential null access warning"

(JDK 1.6.0_23, Eclipse 3.7.0 with "Potential null pointer access" warning level at "Warning") Consider the following example code:

Object obj = null;
for (;;) {
    obj = getObject();
    if (obj != null) break;
    Thread.sleep(25);
}
obj.toString();

I'm getting the following warning on the last line: Potential null pointer access: The variable obj may be null at this location. Is there any real way for obj to actually be null or why the compiler thinks so?

like image 400
Alex Abdugafarov Avatar asked Jun 26 '26 06:06

Alex Abdugafarov


1 Answers

I'd say the compiler sees this as:

Object obj = null;
[Too dumb to interpret this loop]
obj.toString();

So obj.toString() could be null if you cannot interpret what the loop does.

For example you can trick the compiler by replacing:

void x(int x){
    return;  
    x++;  //error unreachable code
}

with

void x(int x){
    if(true) return;
    x++;  //compiles
}
like image 167
Thomas Jung Avatar answered Jun 28 '26 19:06

Thomas Jung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!