The effect of final modifier parameters in Java

Source: Internet
Author: User

The final keyword before the method parameter is to prevent the data from being modified in the method body.

There are two main cases: first, the basic data type is decorated with final, and second, the reference type is decorated with final.

In the first case, the modifier base type (non-reference type). At this point the value of the parameter cannot be modified in the body of the method, i.e. it cannot be re-assigned. Otherwise the compilation will not pass. For example:

1 public static void valid (final int ag) {2 ag=9;3 ag=10;4}

Error message:


In the second case, the reference type is modified. In this case, the object referenced by the parameter variable cannot be changed. As a copy of the reference, the parameter cannot reference the new object in the method body. Otherwise the compilation does not pass. For example:

1 public static void valid (final string[] ag) {2 ag=new string[9];3}

This tip is the same as above. : " The final local variable param2 cannot be assigned. It  Must be blank and not using a compound assignment. "

But for references, if I were, I wouldn't have reported anything wrong, I could have compiled it all through.

1 public static void valid (final string[] ag) {2 ag[0]= "5"; 3 System.out.println (AG); 4}

So, the final keyword, if you want to use the basic type, or very useful. Reference type, or forget it.

The effect of final modifier parameters in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.