Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use the "final" modifier when creating Date objects? [duplicate]

Tags:

java

Possible Duplicate:
When should one use final?

When should Java programmers prefer to use

final Date now = new Date();

over

Date now = new Date();
like image 534
Zango Avatar asked Apr 02 '12 16:04

Zango


2 Answers

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).

like image 182
assylias Avatar answered Sep 19 '22 12:09

assylias


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.

like image 37
Sam DeHaan Avatar answered Sep 21 '22 12:09

Sam DeHaan