
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is a Final Parameter in Java
In this article, we will learn about the final parameter in Java. In Java, you can pass final variables as parameters to methods. The final keyword can be used with variables, methods, and classes to add restrictions on their behavior.
What is a Final Parameter?
A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to a different object. However, the data within the object can be changed. So, the object's state can be changed but not the reference. With variables, the final modifier often is used with static to make the constant a class variable.
Final as a Parameter
The following are the steps to declare final as a parameter in Java ?
- The sample() method takes one parameter: final int data.
- The main() method creates a Test instance and calls sample(500).
- Inside sample(), we can read data (printing it) but cannot modify it.
Example
Below is an example of declaring final as a parameter in Java ?
public class Test{ public void sample(final int data){ System.out.println(data); } public static void main(String args[]) throws Exception{ Test t = new Test(); t.sample(500); } }
Output
500
What Happens If We Try to Modify?
If we attempted to modify the data ?
public void sample(final int data) { data = 600; System.out.println(data); }
The compiler would reject this with an error: "cannot assign a value to final variable data"
Conclusion
Final parameters in Java provide a simple way to provide immutability within the methods. While not always necessary, they can improve code clarity and any attempt to modify it will result in a compilation error.