Interview question: when a variable is modified using the final keyword, can the reference not be changed, or can the referenced object not be changed ?, Final keywords

Source: Internet
Author: User

Interview question: when a variable is modified using the final keyword, can the reference not be changed, or can the referenced object not be changed ?, Final keywords

/** Question: when you use the final keyword to modify a variable, whether the reference cannot be changed or the referenced object cannot be changed * answer: * when you use the final keyword to modify a variable, the guiding variables cannot be changed. The content in the object to which the referenced variables point can still be changed. */Public class Test10 {// final modifies the variable public static final char CHAR = '中' of the basic type '; // final modifier public static final StringBuffer a = new StringBuffer ("StringBuffer"); public static void main (String [] args) {// compilation error, reference cannot be changed // a = new StringBuffer ("hehe"); // the content of the object to which the referenced variable points can still be changed.. append ("xxx");} public static int method1 (final int I) {// I = I + 1; // compilation error, because final modifies the return I;} variable of the basic type. // when someone defines a method parameter (reference a variable, you may want to use the following method to prevent internal modification of the passed parameter object. // In fact, this cannot be done, in this method, you can add the following code to modify the parameter object public static void method2 (final StringBuffer buffer) {buffer. append ("buffer"); // compiled because final modifies the variable of the reference type }}

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.