Java instantiation methods and their differences

Instantiation method:

		String FOREVER_GWC_FIRST = "FOREVER_GWC";
		
		String FOREVER_GWC_SECOND = new String("FOREVER_GWC");

The first method is just an assignment statement. At the time of creation, the JVM checks whether the string already exists in the string pool. If it exists, return the reference of the string to the variable "FOREVER_GWC_FIRST". If it does not exist, create a "FOREVER_GWC" string object and assign it to "FOREVER_GWC_FIRST". Therefore, the statement may only create 1 or 0 objects.

The second method splits new String ("FOREVER_GWC") into two parts, one is "FOREVER_GWC", and the other is new String (). If the "FOREVER_GWC" string already exists in the string pool, then there is no need to create the object again, but the new String statement will construct another string that is the same as "FOREVER_GWC" and put it on the heap. Therefore, this statement will create 1 or 2 objects in memory.

In general, it is recommended to use the String A = "B" method, because this method uses the string buffer pool mechanism, which is more efficient.

Published 19 original articles · praised 0 · visits 1616

Guess you like

Origin blog.csdn.net/FOREVER_GWC/article/details/104856146