I spent more and more time doing Java development during the last months. I really like this language because I think its syntax is the right balance between advanced concept expression and readability. And I must also say that it’s nice being able to assert a 12 years Java programming experience when the technology itself is 12 years old ! I was introduced to it at the time by Stéphane Fritsch, a former university friend of mine who was ecstatic about the perspectives it was already offering at the time.
Today I faced a something that I didn’t see before: the use of final local variables and method parameters.
I was using the const keyword in method signatures a lot when developing C++ code, but I never thought about the use of final variables in Java, except for static constants. This modifier will forbid any change in the variable reference. Nice optimization in theory, but what’s really the point since this won’t affect the code execution much as we are only manipulating object references (as opposed to const objects in C++). Well, I discovered on the jGuru website that this was mandatory to share a variable value with a local inner class:
public void setText(
final String str) {
final JLabel label = new JLabel();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
label.setText(str);
}
});
}
Another point that bugged me often is the way people fail to get the true meaning of the finally block in an try/catch/finally exception management code. When asked, most of the people will explain the finally block like “the code that will be executed after the try and any of the potential catch blocks”. Ok with this, but what’s the point in doing a specific block for this instead of simply writing code directly after the try/catch block ? It would also be executed after all the rest too…
The difference is that the finally block will be executed even if a catch block raises an exception.
System.out.println(“A-start”);
try {
System.out.println(“A-try”);
B(); // this method will raise an exception
} catch (Exception e) {
System.out.println(“A-catch”);
throw new RuntimeException(“Another exception”);
} finally {
System.out.println(“A-finally”);
}
System.out.println(“A-end”);
This will output:
A-start
A-try
B-start
A-catch
A-finally
Exception in thread “main” java.lang.RuntimeException: Another exception
at Finaltest.A(Finaltest.java:13)
at Finaltest.main(Finaltest.java:33)
Thus asserting that the finally block was executed after the try/catch blocks and before the parent exception handling.