Possible Duplicate:
When should one use final?
When should Java programmers prefer to use
final Date now = new Date();
over
Date now = new Date();
Apart from deciding if a variable should be final or not which is covered in other posts, I think the problem with final Date now = ...
, is that although the reference to now will not change (it is final), its value might. So I find this a little misleading for developers who don't know that Date is mutable.
For example, you could write:
public static void main(String[] args) {
final Date now = new Date();
System.out.println(now);
now.setHours(5);
System.out.println(now);
}
and get 2 different dates out of your final date...
Now this is true for any mutable variable (the content of final List<String> l
can change too), but I think in the case of a Date, it is way too easy to assume immutability.
A better solution would be using the joda time library:
final DateTime now = new DateTime();
in this case, now
is immutable and won't change (reference & value).
In Java, a final
variable is a variable whose value, once assigned, cannot be changed. You declare a variable final
when that variable will be assigned a value, and you will never need to change that value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With