How to tell Java that a variable cannot possibly be null?

Fabian Röling :

I have a program that basically looks like this:

boolean[] stuffNThings;
int state=1;
for(String string:list){
   switch(state){
      case 1:
         if(/*condition*/){
            // foo
            break;
         }else{
            stuffNThings=new boolean[/*size*/];
            state=2;
         }
      // intentional fallthrough
      case 2:
         // bar
         stuffNThings[0]=true;
   }
}

As you, a human, can see, case 2 only ever happens when there was previously a state 1 and it switched to state 2 after initialising the array. But Eclipse and the Java compiler don't see this, because it looks like pretty complex logic to them. So Eclipse complains:

The local variable stuffNThings may not have been initialized."

And if I change "boolean[] stuffNThings;" to "boolean[] stuffNThings=null;", it switches to this error message:

Potential null pointer access: The variable stuffNThings may be null at this location.

I also can't initialise it at the top, because the size of the array is only determined after the final loop in state 1.

Java thinks that the array could be null there, but I know that it can't. Is there some way to tell Java this? Or am I definitely forced to put a useless null check around it? Adding that makes the code harder to understand, because it looks like there may be a case where the value doesn't actually get set to true.

Fabian Röling :

After just trying to execute the code regardless of Eclipse complaining, I noticed that it does indeed run without problems. So apparently it was just a warning being set to "error" level, despite not being critical.
There was a "configure problem severity" button, so I set the severity of "Potential null pointer access" to "warning" (and adjusted some other levels accordingly). Now Eclipse just marks it as warning and executes the code without complaining.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324791&siteId=1