I have the following code:
String serviceType;
ServiceBrowser tmpBrowser;
for (String playerName: players) {
serviceType = "_" + playerName + "._tcp";
tmpBrowser = BrowsersGenerator.getBrowser(serviceType);
tmpBrowser.browse();
System.out.println(tmpBrowser.getStatus());
}
System.out.println(tmpBrowser.getStatus());
The compiler complains about the las开发者_如何学JAVAt line. It writes "variable tmpBrowser might not been initialized". If I comment the last line the compile does not complain.
If there are no players
, then the tmpBrowser
won't be initialized at any way. The compiler can't predict if there are any players or not. Also, in contrary to fields (class/instance variables declared outside method blocks), local variables (declared inside method blocks) won't be preinitialized with default values. You need to make the compiler happy by preinitializing it yourself:
ServiceBrowser tmpBrowser = null;
(don't forget to do a nullcheck before getStatus()
, else you may risk a NPE).
Because it really might not been initialized if players is an empty collection.
If you never enter the for loop say when the players
array is empty, the variable tempBrowser
will remain uninitialized. So to overcome this you need to ensure that tempBrowser
has a value assigned to it irrespective of the loop. Something like:
ServiceBrowser tmpBrowser = null;
before the loop will help.
If the number of elements in the players
variable is zero, the loop won't be executed, thus the tmpBrowser
variable will never have been initialized (not even the null
value) when the System.out.println()
call is executed.
The only way to solve the error is to give the tmpBrowser variable a meaningful default (if only even to have null
, but you'll still have a NullPointerException
raised by the tmpBrowser.getStatus()
in that case) if you can't get rid of the last System.out.println(tmpBrowser.getStatus());
call.
精彩评论