The effect of the final keyword on the JVM class loader

Source: Internet
Author: User

It is well known that when accessing a variable or method of a class, if the class is not initialized, a class is initialized first.


However, when the variable of this class is final, it is not necessarily


Take a look at the following example

Package Com.lala.shop;import Java.util.random;public class App {public    static void Main (string[] args)    {        System.out.println (USER.C);    }} Class User{public static final int b = new Random (). Nextint (one);p ublic static final int c = 20;STATIC{SYSTEM.OUT.PRINTLN (" User static init ... ");}

When accessing

System.out.println (USER.C);

, there is no output of "User static init ..."

Because C is a static final variable, and it is equal to 20, you can know its value at compile time, so accessing the value of a directly does not cause the initialization of the user class.


When accessing

System.out.println (USER.B);

, the output is "User static init ..."

This static final variable B is not known for its exact value at compile time, so it can only be known until it is run, so it accesses
USER.B will cause initialization of the user class. That is, static code is loaded quickly.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The effect of the final keyword on the JVM class loader

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.