Search code examples
javavariablesfinal

Java use of non-final variable to set final variable


This is probably a dumb question, but I'll risk asking it anyway.

Often I need to create a final variable for use somewhere else and the value of that variable will need to be set based on some condition. This is how I typically do it:

String notFinalVersion = null;
if (someThing == 1) {
    notFinalVersion = "The value was 1.";
} else {
    notFinalVersion = "The value is not 1.";
}
final String finalVersion = notFinalVersion;

I can then use the variable finalVersion where I need to. But, this just seems somehow wrong. Is there a better way to do this?

Edit: By "better", I meant that I was looking for a method for defining the final variable that did not require that I create an extra variable. I knew that creating an extra variable was inefficient and not a good practice, and I was positive that there must be a way of doing what needed to be done without the extra steps.

I received an answer, which I have marked as accepted. As I stated in my comment, I had originally tried the solution provided, but received an error from Eclipse. I must have either typed it incorrectly the first time, or Eclipse has something of a "hiccup".

I accept that there are many ways of doing something and that what one person will accept as the best way is not what someone else would consider. However, all of the answers included here, were clear and to the point and, I feel, solved my problem.


Solution

  • You can declare a final variable and not assign it yet, as long as it is definitely assigned before you use it. Don't assign it null to begin with, else it will be definitely assigned already. Assign it as you are already doing with your if/else blocks, and you'll be fine.

    final String finalVersion;
    if (someThing == 1) {
        finalVersion = "The value was 1.";
    } else {
        finalVersion = "The value is not 1.";
    }