What is the purpose having final keyword in method parameter? [duplicate]

StackOverflow https://stackoverflow.com/questions/22776423

  •  25-06-2023
  •  | 
  •  

Question

I recently saw a method like

public void display(final String toDisplay){

}

I want to know the purpose of final keyword in method parameter.

Était-ce utile?

La solution

final variables means you can not change the value.

For example final int x=9; and after that if you change it with x=6; then it will not compile.

So in your case

public void display(final String toDisplay){

}

In this method you are allowing a String argument and after that within that method if you try to change then it will not compile.

Autres conseils

suppose your method doing complex calculation so by accidentally you may not change the value of toDisplay variable this is the main reason I can say.

It is to make sure that the implementation will not change the reference.

It simply tells the compiler that this method can not change the thing that parameter points to.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top