[JAVA] final variables that can be directly replaced during the compilation period, and final variables compiled by java

Source: Internet
Author: User

[JAVA] final variables that can be directly replaced during the compilation period, and final variables compiled by java

1. If the following three conditions are met, a final variable is no longer a variable, but a direct amount.

Ii. Under what circumstances can the initialization value be determined during the compilation period?

The assigned expression is only a basic arithmetic expression or string link operation. It does not access common variables and calls methods.

Package fianlFieldCase; public class Test {public static void main (String [] args) {final String str1 = "final" + "field"; final String str2 = "java" + 8; // The str3 value below cannot be final String str3 = "java" + String during compilation because the method is called. valueOf (8); final int a = 2 + 3; final double B = 1.5/3; System. out. println ("java8" = str2); System. out. println ("java8" = str3 );}}

The compiled class file is as follows:

From the compiled results, we can see that except for str3, the values of other variables can be determined during compilation. Because str2 is a direct volume, it is directly replaced with "java8", str2 points to "java8" in the String constant pool ", therefore, when "java8" and str2 are =, true is returned directly. However, the str3 value can only be determined at runtime, so it cannot point to the "java8" in the constant pool.

  The constant pool is used to manage some data that is identified during the compilation period and saved in the compiled class file. It includes constants in classes, methods, and interfaces, as well as string constants.

For example, if String a = "java" is executed, a "java" will be cached in the String constant area. If String B = "java" is executed again ", B directly points to the cached "java ". So a = B returns true.

 

  

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.