difference between “final static string” and “static string”?
consider the following declaration at the top of a class:
the compiler generates a class initializer method that is executed when the class is first used. the method stores the value 42 into intval, and extracts a reference from the classfile string constant table for strval. when these values are referenced later on, they are accessed with field lookups.
we can improve matters with the "final" keyword:
the class no longer requires a method, because the constants go into static field initializers in the dex file. code that refers to intval will use the integer value 42 directly, and accesses to strval will use a relatively inexpensive "string constant" instruction instead of a field lookup.
note: this optimization applies only to primitive types and string constants, not arbitrary reference types. still, it's good practice to declare constants static final whenever possible.
1) final static string: when you say final it's a constant and you can not alter it's value throughout the program. it's not a variable, you can not change it's value. in java we use final keyword to declare constants. we are supposed to follow all uppercase with underscores to separate the words while declaring constants. for e.g.: max_input_time, connection_pool_size, max_user etc.
2) static string: you can use static for member variables of a class and not for local variables. static variables are static and are accessible even w/o creating a instance of the class. so you can use them either by object.<static_variable_name> or classname.<static_variable_name>. they are accessible and hold the same value for all instances of the class.
從編譯的角度來看
源碼:
編譯之後:
我們可以看到在使用str_static_final變量的地方會被替換成"abc_def"。