Possible Duplicate:
When should one use final?
When should Java programmers prefer to use
final Date now = new Date();
over
Date now = new Date();
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.
When you use final keyword you can never change the value of variable.Same apply for date.
A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to an different object.
However the data within the object can be changed. So the state of the object can be changed but not the reference.
With variables, the final modifier often is used with static to make the constant a class variable. Example:
class Test{
final int value=10;
// The following are examples of declaring constants:
public static final int BOXWIDTH = 6;
static final String TITLE = "Manager";
public void changeValue(){
value = 12; //will give an error
}
}
if your requirement is of this type than you can use final with date.
If you declare a field, which is read-only, and you want to have a class thread-safe - then you should use the final
modifier. Sometimes you're forced to make a variable final, if it's used in an anonymous class. In all other cases it doesn't really matter.