Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures Getting There Class Review

Simon Andersson
Simon Andersson
6,880 Points

Why not use the keyword final?

Hello.

As the title says, I'm just curious why we don't use the keyword final in our member variables? Would it hurt or in any way make our code worse? I understand that we can't change the member variables outside the class however.

3 Answers

The final keyword is associated with a variable that never changes. If I wanted to set up a variable for pi I would write it like this:

final double pi = 3.14;

I would assign this variable as final because I know that this number never changes and I wouldn't want it to.

If you have a variable that you don't want to change then you can assign it as final. If you have a fixed interest rate, say 4.99% you can assign it as a final.

If you have a variable called gasPrice, you wouldn't want to make it a final because as you know it never stays the same lol.

Simon Andersson
Simon Andersson
6,880 Points

Okay yeah seems logical. But is it enough to just skip creating a setter for a regular member variable that you only want to retrieve information from and not be able to change? Shouldn't you make this final? Or perhaps then if you don't initialize it in the declaration you can't set it in the constructor?

That is a very good question. From my understanding when you declare a variable final it allows the program to run more efficiently and it also helps add more meaning to your program which in turns helps other programmers to better understand the overall context of your program. Also, my professor in college told me that if you can declare something final in a program then do it.

Simon Andersson
Simon Andersson
6,880 Points

I'll keep what your professor told you as a good rule of thumb. This is why I got confused since the variable should not be changed, only displayed, therefore to me it seems like a good thing make it a final. =)

Dan Jones
Dan Jones
7,899 Points

Google says "In the Java programming language, the final keyword is used in several different contexts to define an entity which may only be assigned once. Once a final variable has been assigned, it always contains the same value." I suspect what that refers to is a "constant." I remember in an earlier lesson, something with the keyword "final" was named in all capitals, example "MAX_VALUE"