The content of this article is about how to understand the parameters in JAVA methods and use final to modify them. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The reason why parameters in JAVA methods are modified with final
Many people say that the reason for using final to modify method parameters in JAVA is to prevent method parameters from being tampered with when calling. In fact, it is not This is the reason, but there may be ambiguities in understanding. Some people think that the actual value of the variable where the statement is called will not be modified. Another understanding is that it cannot be modified only within the calling method.
In fact, the first understanding is wrong. For basic types, it has the same effect whether it is modified with final or not at the place of call, such as the following code:
publi cstatic void main(String hh[]) { int i = 1; System.out.println(i); checkInt(i); System.out.println(i); } public static void checkInt(final int i) { //do something } |
You set the parameters in the checkInt() method to final and non-final effects It's the same for the calling place.
However, it is the same for reference types. Whether it is modified or not, the reference address will not be changed, but the attribute value of the reference variable can be changed. As follows:
publicstaticvoid main(String hh[]) { LoginInfo login = new LoginInfo(); login.setPassword("1235"); login.setUserName("mygod"); System.out.println("username:"+login.getUserName()+",password:"+login.getPassword()); checkLoginInfo(login); System.out.println("username:"+login.getUserName()+",password:"+login.getPassword()); } publicstaticvoid checkLoginInfo(final LoginInfo login) { login.setUserName("yun"); } |
##For the second statement , it looks like this, I gave this parameter, you can only use the value of this parameter, you cannot modify it, it is the same for basic types and reference types, as follows:
The above is the detailed content of How to understand how to use final to modify parameters in JAVA methods. For more information, please follow other related articles on the PHP Chinese website!