Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Objects Meet Objects Final

You can declare a final variable and later initialize it. How is that possible? What is an example of that?

So, my logic is that if it's final it should be final. What command do we use later initialize that variable? And what are the cases when we cannont assign a new literal to a variable? Thank you for a help!

2 Answers

Your logic is correct final is final BUT only from the moment a value gets assigned. And that moment can be in place:

public static final int MY_VAR = 3;

or later with something like:

public static final int MY_VAR;

and then inside the constructor for example:

MY_VAR = someConstructorArgValue;

In the top example it gets assigned straight away, in the bottom it gets assigned later on, BUT in both cases they can no longer be changed.

Hope it helped

Thank you, Pedro!