Java Programming – Why Declare a String as Final and Then Use It?

finaljavaprogramming practicesvariables

In a typical spring mvc validator class, while inserting an errorCode value in the Errors object, what difference does it make between using a String (props.somefield.req) like so

errors.rejectValue("elementId", "props.somefield.req");

verses a declared static final String ?

private static final String SOMFIELD_REQ = "props.somefield.req"; ...
errors.rejectValue("elementId", SOMFIELD_REQ);

Does it improve the performance even in a slightest way? I have read a few questions on stack overflow (String and final, Does it make sense to define a final String in Java?) but no one got around to answering this questions update question.

Best Answer

At runtime, it does not make a difference.

The point is readability - as a member variable, it likely is declared at the beginning of the class' source code, and making it static means it doesn't have to be allocated for each new instance of the class.

Making it final signifies to the reader that the value will not change (to the compiler too, but that's less important here).

This way, there are no "magic values" buried in the implementation, and if a change is desired to the "constant", it only needs to be changed in one place.

This basically mimics what a C programmer would do with a #define.

Related Topic