Personal memo-Final Modifier

Source: Internet
Author: User
Public class finaltest {Public String findword = "final word"; public final stringbuffer sfindword = new stringbuffer ("final word "); /*** @ Param ARGs */public static void main (string [] ARGs) {finaltest Ft = new finaltest (); system. out. println (FT. findword. hashcode (); ft. findword + = "DD"; system. out. println (FT. findword. hashcode (); system. out. println (FT. sfindword. hashcode (); ft. sfindword. append ("DD"); system. out. println (FT. sfindword. hashcode ());}}

The running result is:

-1919389836
-1992659212
14576877
14576877

The final modifier points to a fixed address and cannot represent a fixed value.

It can be seen that final is only valid for the referenced "value" (that is, the memory address of the object it points to), and it forces the reference to only point to the object initially pointed, changing the point will cause compilation errors. Final is not responsible for the changes to the objects it points. This is similar to the = Operator: = Operator is only responsible for the equal value of the referenced "value". As to whether the content of the object pointed to by this address is equal, the = operator does not matter. Understanding final issues has important meanings. ManyProgramAll vulnerabilities are based on this ---- final can only ensure that the reference always points to a fixed object, but cannot ensure that the state of that object remains unchanged. In multi-threaded operations, an object will be shared or modified by multiple threads. Unintentional modifications made by one thread to the object may cause another thread to crash. The solution to an error is to declare the object as final when it is created, so that it is "never changed ". In fact, it is futile.

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.