I am trying to write a static method that returns a string of my computer\'s MAC address (the function itself was found here: http://www.mkyong.com/java/how-to-get-mac-address-i
All branches must return something, just add a return null;
at the end:
static String returnMacAddress(){ // 1.
InetAddress ip;
try{ // 2.
ip = InetAddress.getLocalHost(); // 3. (until return stmt)
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
System.out.print("Current MAC address: ");
StringBuilder stringBuilder = new StringBuilder();
for(int i = 0; i < mac.length; i++){
stringBuilder.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
return stringBuilder.toString(); // 4.
}catch(UnknownHostException e){ // 5.
e.printStackTrace(); // 6.
} catch(SocketException e){
e.printStackTrace();
}
return null; // 7.
}
This is syntactically correct - but you have to think about what this means semantically, and if that is the desired operation:
EDIT
How the control flows in this case - as OP asked if the return null
at the end would negate the previous value, in a successful execution:
finally
block, that would be executed now, and that could even overwrite the returned value...)In unsuccessful case, (UnknownHostException for example):
finally
block, that would be executed now, and that could even overwrite the returned value...)null
value is returned to the previous stack frame (7. in code)As you see, in successful case, the return null;
statement, even though it is after the "real return", doesn't influence the returned value. Whenever a return is reached, the eecution of the current block is stopped. (and if there is one in the actual context, the appropriate finally block will get the control).
The finally
block is tricky though: read up on that, it will be useful knowledge.