As mentioned, final is used with a Java method to mark that the method can't be overridden (for object scope) or hidden (for static). This allows the original developer to create functionality that cannot be changed by subclasses, and that is all the guarantee it provides.

This means that if the method relies on other customizable components like non-public fields/methods the functionality of the final method may still be customizable. This is good though as (with polymorphism) it allows for partial customization.

There are a number of reasons to prevent something from being customizable, including:

  • Performance -- Some compilers can analyse and optimise the operation, especially the one without side-effects.

  • Obtain encapsulated data -- look at immutable Objects where their attributes are set at the construction time and should never be changed. Or a calculated value derived from those attributes. A good example is the Java String class.

  • Reliability and Contract -- Objects are composed of primitives (int, char, double, etc.) and/or other Objects. Not all operations applicable to those components should be applicable or even logical when they are used in the bigger Object. Methods with the final modifier can be used to ensure that. The Counter class is a good example.


public class Counter {
    private int counter = 0;

    public final int count() {
        return counter++;
    }

    public final int reset() {
        return (counter = 0);
    }
}

If the public final int count() method is not final, we can do something like this:

Counter c = new Counter() {   
    public int count() {
        super.count();   
        return super.count();   
    } 
}

c.count(); // now count 2

Or something like this:

Counter c = new Counter() {
    public int count() {
        int lastCount = 0;
        for (int i = super.count(); --i >= 0; ) {
            lastCount = super.count();
        }

        return lastCount;
    }
}

c.count(); // Now double count
Answer from NawaMan on Stack Overflow
Top answer
1 of 5
167

As mentioned, final is used with a Java method to mark that the method can't be overridden (for object scope) or hidden (for static). This allows the original developer to create functionality that cannot be changed by subclasses, and that is all the guarantee it provides.

This means that if the method relies on other customizable components like non-public fields/methods the functionality of the final method may still be customizable. This is good though as (with polymorphism) it allows for partial customization.

There are a number of reasons to prevent something from being customizable, including:

  • Performance -- Some compilers can analyse and optimise the operation, especially the one without side-effects.

  • Obtain encapsulated data -- look at immutable Objects where their attributes are set at the construction time and should never be changed. Or a calculated value derived from those attributes. A good example is the Java String class.

  • Reliability and Contract -- Objects are composed of primitives (int, char, double, etc.) and/or other Objects. Not all operations applicable to those components should be applicable or even logical when they are used in the bigger Object. Methods with the final modifier can be used to ensure that. The Counter class is a good example.


public class Counter {
    private int counter = 0;

    public final int count() {
        return counter++;
    }

    public final int reset() {
        return (counter = 0);
    }
}

If the public final int count() method is not final, we can do something like this:

Counter c = new Counter() {   
    public int count() {
        super.count();   
        return super.count();   
    } 
}

c.count(); // now count 2

Or something like this:

Counter c = new Counter() {
    public int count() {
        int lastCount = 0;
        for (int i = super.count(); --i >= 0; ) {
            lastCount = super.count();
        }

        return lastCount;
    }
}

c.count(); // Now double count
2 of 5
30

What kind of "contract" does a final method promise?

Look at it the other way, any non final method makes the implicit guarantee that you can override it with your own implementation and the class will still work as expected. When you can't guarantee that your class supports overwriting a method you should make it final.

🌐
BeginnersBook -
beginnersbook.com › home › java › final keyword in java – final variable, method and class
Final Keyword In Java – Final variable, Method and Class
November 5, 2022 - Dude, if you want only one of the methods of a super class to be not overridden by subclass, you need to mark the method as abstract instead of marking the class as final (which makes it not inheritable). And if you want all the methods in a super class to be not overridden but be available for sub class to access), u need to use abstract keywords for all abstract methods. ... i like your website because every topic is simply represent with an good and useful example, that why everything gonna be easier to understand….
Discussions

java - Why declare final variables inside methods? - Software Engineering Stack Exchange
If you are declaring fields in ... in a method, then it's possible for multiple threads to access those fields at the same time. There are some obscure exceptions, but in general, if a field is final, then every thread that uses your class will see the same value for the variable. Conversely, if a field is not final and multiple threads are using your class, you will need to worry about explicit synchronization using synchronized blocks and/or classes from java.util.co... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
October 22, 2011
Using final in method parameters - your opinion?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnjava
8
2
September 13, 2024
coding style - In Java, should I use "final" for parameters and locals even when I don't have to? - Software Engineering Stack Exchange
Java allows marking variables (fields / locals / parameters) as final, to prevent re-assigning into them. I find it very useful with fields, as it helps me quickly see whether some attributes - or an More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
February 16, 2011
Final, static, and static final in Java
If you make a variable or method static, it would only be accessed by the class itself and not by an instance of the class (object) This is already not true. A static variable can be accessed by instances of the class perfectly fine. I guess your further confusion results from this misunderstanding. A static class variable will be created once for the class, and not once for every instance. More on reddit.com
🌐 r/learnprogramming
3
1
September 28, 2021
🌐
Tutorialspoint
tutorialspoint.com › java › final_keyword_in_java.htm
Java - final Keyword
You declare methods using the final modifier in the class declaration, as in the following example − · class FinalTester { int value = 10; public final void changeValue() { value = 12; } } public class Tester extends FinalTester { public void changeValue() { value = 14; } public static void ...
🌐
Scaler
scaler.com › topics › final-method-in-java
Final Method in Java - Scaler Topics
June 22, 2022 - When we want that the content of a method should not change by any outsider or child class, then we declare the method as the final method in java. When a method is declared as the final method in the parent class, then any child class cannot override or modify the final method in java.
🌐
DataCamp
datacamp.com › doc › java › final
final Keyword in Java: Usage & Examples
This keyword plays a crucial role in ensuring immutability and preventing inheritance or method overriding. A final variable is a constant; once initialized, its value cannot be changed. ... A final variable must be initialized when it is declared or within a constructor if it is an instance variable.
🌐
Oracle
docs.oracle.com › javase › tutorial › java › IandI › final.html
Writing Final Classes and Methods (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)
You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this—a number of its methods are final. You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object. For example, you might want to make the getFirstPlayer method in this ChessAlgorithm class final:
Find elsewhere
🌐
Baeldung
baeldung.com › home › java › core java › the “final” keyword in java
The "final" Keyword in Java | Baeldung
June 14, 2025 - Consider the situation if we can extend the String class, override any of its methods, and substitute all the String instances with the instances of our specific String subclass. The result of the operations over String objects will then become unpredictable. And given that the String class is used everywhere, it’s unacceptable. That’s why the String class is marked as final. Any attempt to inherit from a final class will cause a compiler error. To demonstrate this, let’s create the final class Cat:
🌐
Programiz
programiz.com › java-programming › final-keyword
Java final keyword (With examples)
Once any entity (variable, method or class) is declared final, it can be assigned only once. That is, the final variable cannot be reinitialized with another value ... In Java, we cannot change the value of a final variable. For example,
🌐
Wikipedia
en.wikipedia.org › wiki › Final_(Java)
final (Java) - Wikipedia
October 29, 2025 - // final in a class declaration declares that a class cannot be extended class Z final : public X, public Y { public: // final in a method signature declares that a method cannot be overridden further void someOperation() override final { // do something here } };
🌐
TechVidvan
techvidvan.com › tutorials › java-final-keyword
Java Final Keyword, Variable, Method and Class - TechVidvan
June 15, 2020 - The above example of the Final Method generates a compile-time error. As the Parent class Final method was overridden by the Child class Final method; that is not possible in the Java programming language.
🌐
W3Schools
w3schools.com › java › ref_keyword_final.asp
Java final Keyword
The final keyword is useful when you want a variable to always store the same value, like PI (3.14159...). The final keyword is called a "modifier". You will learn more about these in the Java Modifiers ...
Top answer
1 of 7
68

I would say that this is due to force of habit. The programmer that wrote this code knew as he was writing it that the values for the final variables should never be changed after assignment, and so made them final. Any attempt to assign a new value to a final variable after assignment will result in a compiler error.

As habits go, it's not a bad one to develop. At the least, making a variable final specifies the intent of the programmer at the time of writing. This is important as it might give subsequent programmers who edit the code pause for thought before they start changing how that variable is used.

2 of 7
54

Speaking as a Java developer who makes all variables final by default (and who appreciates the fact that Eclipse can do this automatically), I find it easier to reason about my program if variables are initialized once and never changed again.

For one thing, uninitialized variables are no longer any concern, because trying to use a final variable before it has been initialized will result in a compile error. This is particularly useful for nested conditional logic, where I want to make sure that I covered all the cases:

final int result;
if (/* something */) {
  if (/* something else */) {
    result = 1;
  }
  else if (/* some other thing */) {
    result = 2;
  }
}
else {
  result = 3;
}
System.out.println(result);

Did I cover all the cases? (Hint: No.) Sure enough, this code won't even compile.

One more thing: In general, any time you know that something is always true about a variable, you should try to get your language to enforce it. We do this every day when we specify a variable's type, of course: The language will ensure that values that are not of that type cannot be stored in that variable. Likewise, if you know that a variable should not be reassigned because it already has the value that it should keep for the entire method, then you can get the language to enforce that restriction by declaring it final.

Lastly, there's the matter of habit. Others have mentioned that this is a habit (+1 to Jon for that), but let me say something about why you would want this habit. If you are declaring fields in your class and not local variables in a method, then it's possible for multiple threads to access those fields at the same time. There are some obscure exceptions, but in general, if a field is final, then every thread that uses your class will see the same value for the variable. Conversely, if a field is not final and multiple threads are using your class, you will need to worry about explicit synchronization using synchronized blocks and/or classes from java.util.concurrent. Synchronization is possible, but programming is hard enough already. ;-) So, if you just declare everything final out of habit, then many of your fields will be final and you'll spend as little time as possible worrying about synchronization and concurrency-related bugs.

For more on this habit, check out the "Minimize Mutability" tip in Joshua Bloch's Effective Java.

Edit: @Peter Taylor has pointed out that the example above would also not compile if the final keyword is removed, which is completely correct. When I advised in favor of keeping all local variables final, it's because I wanted to make examples like the following one impossible:

int result = 0;

// OK, time to cover all the cases!
if (/* something */) {
  if (/* something else */) {
    result = 1;
  }
  else if (/* some other thing */) {
    result = 2;
  }
  // Whoops, missed an "else" here. Too bad.
}
else {
  result = 3;
}
System.out.println(result);  // Works fine!

Using a new variable instead of reusing an old one is how I can tell the compiler that trying to cover the complete universe of possibilities, and using final variables forces me to use a new variable instead of recycling an old one.

Another valid complaint about this example is that you should avoid complex nested conditional logic in the first place. That's true, of course, precisely because it's hard to make sure you covered all the cases in the way that you intended. However, sometimes complex logic can't be avoided. When my logic is complex, I want my variables to be as simple to reason about as possible, which I can achieve by making sure my variables' values never change after they are initialized.

🌐
GeeksforGeeks
geeksforgeeks.org › java › final-keyword-in-java
final Keyword in Java - GeeksforGeeks
The final keyword is a non-access modifier used to restrict modification. It applies to variables (value cannot change) methods (cannot be overridden) and classes (cannot be extended).
Published   5 days ago
🌐
Reddit
reddit.com › r/learnjava › using final in method parameters - your opinion?
r/learnjava on Reddit: Using final in method parameters - your opinion?
September 13, 2024 -

Hi there.

In my company people tend to add final to method parameters all over the codebase.

At the same time I believe they don't do it because of any gain it gives them, but just because maybe they were learnt to do so in some course or bootcamp.

I don't see a reason to add final to method arguments in 99% as I tend to program in a way, were you return new object back from the method (so no modification of method parameters) or you design a method in a way that it is obvious that it can change the internals of the passed objects.

Can you convince me that declaring final to method parameters has its upsides and I should change my attitude, or I am the one who is on the right side?

Happy to hear your opinions.

Top answer
1 of 6
9
I don't like the "right" or "wrong" approach here. There are no right or wrong, just different ways to think about things. The reason you'd want to use final is because it makes it clear that you're not changing the value. You can be confident that throughout the method, you can trust that the value remains the same. It is one way to enforce immutability within the method itself. Is it a massive gain? No. IMHO, it is more about communication than functionality. It communicates to the the people using those methods that you won't tamper with whatever you're sending in, which already seems to be your style. However, it is also good practice to follow your team's codestyle. The worst codebases are written with conflicting philosophies and ideas. Two half-baked good ideas is worse than one ok idea that has been committed to. Consistency is important, and you not using final might undermine other developer's trust in the code when they see methods that doesn't use it. This is one of those "raise the question, get buy-in or adopt the team codestyle" kind of situations. Don't do your own thing if everyone else is doing something different.
2 of 6
2
Reassigning method parameters can lead to confusing code. According to some style guides all method parameters should be marked final to prevent this. Other style guides say not to do it, as it ends up cluttering the method signature. Reassignment is something a linter can easily catch, so I a properly set up environment final (on parameters) is completely useless. Regardless of what you think, you should always follow the conventions of the codebase you're working in, because a bad style guide is better than none at all (once the code base gets big enough). If you work on the codebase for a long time you might be able to propose changes to the style guide to the team.
🌐
Unstop
unstop.com › home › blog › final keyword in java | syntax, uses & more (+code examples)
Final Keyword In Java | Syntax, Uses & More (+Code Examples) // Unstop
October 29, 2024 - Consistent Method Behavior: By marking methods as final, you prevent them from being overridden by potentially unsafe implementations in subclasses, ensuring that the method’s behavior remains secure and predictable. Protected Class Structure: Final classes prevent subclasses from altering the class structure, which is especially important for secure system classes. For example, making String final prevents malicious modifications or subclassing that could affect core functionalities across the application. With this, we conclude our discussion on the final keyword in Java programming.
Top answer
1 of 5
92

I use final the same way as you. To me it looks superfluous on local variables and method parameters, and it doesn't convey useful extra information.

One important thing is that strive to keep my methods short and clean, each doing a single task. Thus my local variables and parameters have a very limited scope, and are used only for a single purpose. This minimizes the chances of reassigning them inadvertently.

Moreover, as you surely know, final doesn't guarantee that you can't change the value/state of a (nonprimitive) variable. Only that you can't reassign the reference to that object once initialized. In other words, it works seamlessly only with variables of primitive or immutable types. Consider

final String s = "forever";
final int i = 1;
final Map<String, Integer> m = new HashMap<String, Integer>();

s = "never"; // compilation error!
i++; // compilation error!
m.put(s, i); // fine

This means that in many cases it still doesn't make it easier to understand what happens inside the code, and misunderstanding this may in fact cause subtle bugs which are hard to detect.

2 of 5
85

Your Java programming style and thoughts are fine - don't need to doubt yourself there.

On the other hand, I find it a lot less useful with locals and parameters, and usually I avoid marking them as final even if they will never be re-assigned into (with the obvious exception when they need to be used in an inner class).

This is exactly why you should use the final keyword. You state that YOU know it'll never be re-assigned, but no one else knows that. Using final immediately disambiguates your code that tiny bit more.

🌐
Coderanch
coderanch.com › t › 660559 › java › good-programming-practice-final-keyword
Is it a good programming practice to use final keyword in method parameter ? (Java in General forum at Coderanch)
January 7, 2016 - Making argument variables 'final' makes it not possible to modify argument variables (although, if such a variable refers to a mutable object, you could still modify the object that the variable refers to - and such a change would be visible in other parts of the program). If you use an argument variable in an anonymous inner class inside the method (and you're using Java 7 or older), then you are required to make it final, because anonymous inner classes can only access final variables that are defined outside of the anonymous inner class (this restriction was removed in Java 8).
🌐
Reddit
reddit.com › r/learnprogramming › final, static, and static final in java
r/learnprogramming on Reddit: Final, static, and static final in Java
September 28, 2021 -

Please correct me if I am wrong, and explain where my understanding is incomplete.

From what I've read both static and final are keywords. If you make a variable or method static, it would only be accessed by the class itself and not by an instance of the class (object). A static class would be useful if it was nested inside another class and you didn't want an instance of the outer class to access the inner class.

If you make a variable final, then it is initialized once and not changed. A final class can't be subclassed, and a final method can't be overwritten. If a variable is static final, then it cannot be changed and it can only be accessed by the class itself and not an object of the class.

People use static all the time, but why is it useful to limit the access of a method or variable to the class itself and not any instances of it?

Top answer
1 of 9
269

Java always makes a copy of parameters before sending them to methods. This means the final doesn't mean any difference for the calling code. This only means that inside the method the variables can not be reassigned.

Note that if you have a final object, you can still change the attributes of the object. This is because objects in Java really are pointers to objects. And only the pointer is copied (and will be final in your method), not the actual object.

2 of 9
105

There is a circumstance where you're required to declare it final —otherwise it will result in compile error—, namely passing them through into an anonymous class or a lambda. Here's a basic example using an anonymous class:

public FileFilter createFileExtensionFilter(final String extension) {
    FileFilter fileFilter = new FileFilter() {
        public boolean accept(File file) {
            return file.getName().endsWith(extension);
        }
    };

    // Imagine what would happen when we're allowed to change extension here?
    // extension = "foo";

    return fileFilter;
}

And here's the exact same example in lambda flavor:

public FileFilter createFileExtensionFilter(final String extension) {
    FileFilter fileFilter = file -> file.getName().endsWith(extension);

    // Imagine what would happen when we're allowed to change extension here?
    // extension = "foo";

    return fileFilter;
}

Removing the final modifier would result in compile error, because it isn't guaranteed anymore that the value is a runtime constant. Changing the value after creation of the anonymous class or lambda would namely cause the instance of the anonymous class or lambda to behave different after the moment of creation.