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.

Answer from Thirler on Stack Overflow
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.

🌐
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
Discussions

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
oop - Java `final` method: what does it promise? - Stack Overflow
The syntactic constraint is clear to me, but what is the implication in the OOP sense? Is final used correctly in this sense by most class authors? What kind of "contract" does a final method promise? ... As mentioned, final is used with a Java method to mark that the method can't be overridden ... More on stackoverflow.com
🌐 stackoverflow.com
coding style - In Java, should I use "final" for parameters and locals even when I don't have to? - Software Engineering Stack Exchange
I consider final in method parameters and local variables to be code noise. Java method declarations can be quite long (especially with generics) - there's no need to make them any longer. 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
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.

🌐
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.
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.

🌐
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 - The final keyword in Java is used to declare constants, prevent method overriding, and prevent class inheritance, ensuring immutability and stability in code.
Find elsewhere
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.

🌐
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.
🌐
Tutorialspoint
tutorialspoint.com › java › final_keyword_in_java.htm
Java - final Keyword
The final keyword is used to define a constant and to make attributes, methods, and classes final i.e., non-changeable. Methods and classes which are defined as final cannot be inherited and overridden. The final keyword is a non-access modifier.
🌐
TechVidvan
techvidvan.com › tutorials › java-final-keyword
Java Final Keyword, Variable, Method and Class - TechVidvan
June 15, 2020 - As earlier, we discussed the Final Keyword and How to declare the Final Variable. We can declare Java methods as Final Method by adding the Final keyword before the method name. The Method with Final Keyword cannot be overridden in the subclasses.
🌐
Scaler
scaler.com › topics › final-method-in-java
Final Method in Java - Scaler Topics
June 22, 2022 - Whenever 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. The final keyword before the name of a method indicates that the method cannot be overridden by subclasses.
🌐
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?

🌐
W3Schools
w3schools.com › java › ref_keyword_final.asp
Java final Keyword
The final keyword is a non-access ... and methods, which makes them non-changeable (impossible to inherit or override). The final keyword is useful when you want a variable to always store the same value, like PI (3.14159...). The final keyword ...
🌐
DataCamp
datacamp.com › doc › java › final
final Keyword in Java: Usage & Examples
The final keyword in Java is a non-access modifier that can be applied to variables, methods, and classes. It is used to restrict the user from further modifying the entity to which it is applied.
🌐
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 - allen robin wrote:Hey,First of all,Java always makes a copy of parameters before sending them to methods means the final doesn't mean any difference for the calling code i.e., Not true, check your understanding how objects and primitives are processed awhen used as parameters. allen robin wrote: inside the method the variables can not be reassigned.On the other hand, if you reassign any new value within the method the compiler complains immediately.
🌐
Wikipedia
en.wikipedia.org › wiki › Final_(Java)
final (Java) - Wikipedia
October 29, 2025 - It is also used similarly to Java to declare a class as final (cannot be extended). // 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 } };
🌐
Quora
quora.com › In-Java-what-does-final-do
In Java, what does 'final' do? - Quora
Answer (1 of 18): Final Keyword in Java The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be: 1) final variable 2) final method 3) final class 1) final variable final variables are nothing but constants. We cannot change the ...
🌐
Medium
evelinedsouza.medium.com › java-can-final-methods-be-overridden-54b41fe89cb2
Java — Can final methods be overridden? | by Eveline D'souza | Medium
January 31, 2024 - When a method is declared as final in a class, it means that the method implementation in that class is the final version and cannot be changed by any subclasses.