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 last 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 thetmpBrowserwon’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:(don’t forget to do a nullcheck before
getStatus(), else you may risk a NPE).