Differences between final and static final modifier Variables

Source: Internet
Author: User
1. import Java. util. random; 2. 3. // The difference between static final and final is described in this example. 4. public class staticandfinaltest {5. 6. private Static random Rand = new random (47); // 47 is used as a random seed to generate a random number. 7. 8. private Final int A = Rand. nextint (20); 9. 10. private Static final int B = Rand. nextint (20); 11. 12. public static void main (string [] ARGs) {13. staticandfinaltest Sf = new staticandfinaltest (); 14. system. out. println ("SF:" + "A =" + SF. a); 15. system. out. println ("SF:" + "B =" + SF. b); 16. system. out. println ("------------------------------"); 17. staticandfinaltest sf1 = new staticandfinaltest (); 18. system. out. println ("sf1:" + "A =" + sf1.a); 19. system. out. println ("sf1:" + "B =" + sf1. B); 20 .} 21. 22 .}

Running result:

    • SF: A = 15
    • SF: B = 18
    • --------------
    • sf1: A = 13
    • sf1: B = 18

      we can see that in the SF and sf1 objects, the value of A is not unique, however, the value of B is not changed by creating an sf1 object. This is because it is static and has been initialized during loading, rather than initialized every time a new object is created.

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.