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. true or false?

You can declare a final variable and later initialize it. true or false? Please explain

1 Answer

andren
andren
28,526 Points

That statement is true. When you declare a variable with the final keyword it cannot be reassigned (be given a new value) after it has been assigned. But you can leave it empty during the declaration and provide it with it's value later.

Examples:

1:

final String example = "Hello World!"; // Creates a final String set to "Hello World"
example = "Hello!" // This is invalid since the example variable has already been set to "Hello World!"

2:

final String example; // Creates an empty final String
example = "Hello!" // This is valid since the example variable has not been assigned a value yet.
example = "Hello World" // This is invalid since the example variable has already been set to "Hello!"