[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.