“final static String” Vs “static String”

Difference between “final static String” and “static String”?

 

 

Consider the following declaration at the top of a class:

static int intVal = 42;
static String strVal = "Hello, world!";
  • 1.
  • 2.
 
 

 

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:

static final int intVal = 42;
static final String strVal = "Hello, world!";
  • 1.
  • 2.
 
 

 

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.

 

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

 

 

 

从编译的角度来看

源码:

public class DemoA {
	public final static String str_Static_Final = "ABC_DEF";
	public static String str_Static = "DEF_ABC";
	public static void main(String[] args) {
		String strA = str_Static_Final;
		String strB = str_Static;
		System.out.println(strA);
		System.out.println(strB);
	}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
 
 

编译之后:

public class DemoA
{
  public static final String str_Static_Final = "ABC_DEF";
  public static String str_Static = "DEF_ABC";
  
  public static void main(String[] args)
  {
    String strA = "ABC_DEF";
    String strB = str_Static;
    System.out.println(strA);
    System.out.println(strB);
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
 
 

我们可以看到在使用str_Static_Final变量的地方会被替换成"ABC_DEF"。

posted @ 2023-07-28 16:32  CharyGao  阅读(11)  评论(0)    收藏  举报