1

I was reading about the final keyword in Java on Wikipedia here (https://en.wikipedia.org/wiki/Final_(Java)#Final_variables) and was a little confused by the first sentence. It says:

A final variable can only be initialized once, either via an initializer or an assignment statement.

What is an "initializer" in this context? I googled and learned about an "initializer block" which is executed prior to constructors, but I don't think that's what this is referring to since an initializer block would still accomplish assignment with assignment statements. So what is an "initializer" which can do the same work as an assignment statement?

0

3 Answers 3

4

That Wikipedia paragraph is incredibly badly worded. You can either initialise your final variable

  • when you declare it,
  • in an initialiser block after you declare it, outside of any method or constructor, or
  • in a constructor.

You must pick only one of these places. You can't initialise a final variable twice.

Sign up to request clarification or add additional context in comments.

Comments

3

The key word is once. You can do

final int i = 1;

or

final int i;
{
    i = 1;
}

Which is an initialization block; and yes - it will be copied (just as the first example is) into every constructor (including the default if none is explicitly provided).

Comments

-1

That initializer is not referring to an initializer block. It's referring to a field declaration that's accompanied with an initialization expression, as defined in the JLS here. For example,

class Example {
    final Foo theField = new Foo();
}

theField would be a field that has an initializer as opposed to

class Example {
    final Foo theField;
    public Example(Foo foo) {
        this.theField = foo; // a normal assignment
    }
}

The presence of an initializer influences whether a field can be considered a constant variable, a type of constant expression.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.