We have a method whose parameter is defined as final,and then change the value of this parameter(in this method) and return it, it should not be changed as we passed it as final.
But this is not the case.
Please help me to understand this!
public static void main(String[] args) {
EmployeeBean e1 = new EmployeeBean("1", "jitu");
System.out.println("object before set >>" + e1.getEmpName());
EmployeeBean newObj = x.changeFinalvalue(e1);
System.out.println("object after set >>" + newObj.getEmpName());
public EmployeeBean changeFinalvalue(final EmployeeBean x) {
x.setEmpName("Jeet");
return x;
}
Output :
object after set >>jitu
object after set >>Jeet //doubt:it has to be ‘jitu’ only
You are not changing which object is being referred to by the parameter (which is not allowed here). Instead you are changing the state of the object (which is allowed here).
In other words, when you pass your e1 EmployeeBean object into the method, the x parameter refers to the same object that e1 refers to, and within the method, this cannot change, and so you can’t do this:
But what you’re doing — changing the state of the object — is allowed.
The only way that I know to prevent problems like this is to make a deep copy of the object passed in as parameter and work on the copy/clone object. You could also make the EmployeeBean immutable, but then it wouldn’t be much of a Bean, now would it?
Edit: I figured that this question has had to have been asked here many times, and on a little searching, I’ve found that of course it has. Please look at these links for a good discussion on this. Note that this is a general issue about final variables whether they are method parameters or class fields:
java-final-keyword-for-variables
java-final-modifier