I ran PMD on my source code which is somewhat this way
JSONArray jsarray_com = new JSONArray();
Later i am adding some elements to the jsarray_com this way
jsarray_com.put("One");
jsarray_com.put("Two");
Now coming to the question what PMD is suggesting is that declare the JSONArray as final ??
Could you please let me know what advantage will one get if it declared as final
When I made the changes this way
final JSONArray jsarray_com = new JSONArray();
the code is working fine .
PMD has detected that jsarray_com
is never reassigned, so it's suggesting to add final
to the declaration to make this fact explicit. When you see final
, you immediately know that jsarray_com
will always reference the same object. It makes the code slightly easier to follow, but you are free to ignore the suggestion.
Using final
when possible might also help the JVM optimize your code, although this last point is not that relevant. In fact, most JVMs are able to figure this out without any input from the user, in the same way PMD does.
Note that declaring a variable as final
does not prevent you from modifying the object through methods like .put()
. So, for instance, you can do this:
jsarray_com.put("foo");
but not this:
jsarray_com = anotherarray_com;