Comparison of two kinds of assignment methods
1, Direct assignment method : String s1= "abc";
This assignment method uses the most, because it may not need to create an object, or it can be created only once.
It first determines that the string constant pool has no string abc, and if it does not exist, it is saved in a constant pool and pointed to by the S1 object. If the string already exists, you do not need to create the object again.
For example: String s= "abc";
String ss= "ABC";
Then: the S==ss execution result is true, (this method determines whether two objects point to the same address), indicating that a string that already exists in the constant pool is not created again.
2. New Creation Object Method : String S2=new string ("abc");
This method of assignment is rarely used because it creates at least one object at a time, or two times, compared to memory.
It first determines whether the constant pool exists ABC, if it does not exist, you need to save ABC in the constant pool, and then create an object in the heap, altogether created two times.
If the constant pool already exists in ABC, it needs to be created only once in the heap.
Second, the compilation period and the runtime analysis when the string is added
(1) String a= "a";
String a1=a+1;
String b= "A1";
System.out.println (A1==B);
The result is false
Because the values of A and b at compile time can be determined, but A1 is a variable with a constant, but also a variable, it cannot determine the value at compile time, because it cannot determine the value of the variable A, only the run time can be obtained value of A1. So the result is false.
(2) Final String c= "C";
String c1=c+1;
String b1= "C1";
System.out.println (C1==B1);
The result is true.
C is final modified as a constant, B1 is also a constant, so at compile time can determine the value, so C1 is also a constant, the value is "C1", and at compile time can also determine the value, so the result is true.
(3) Final String d=getd ();
String d1=d+1;
String b2= "D1";
System.out.println (D1==B2);
public static String getd () {
return D;
}
The result is false
Although the D is a constant, but it needs to call the method to assign a value, and the calling method only returns the result with the value run period, it cannot determine the value at compile time, D1 cannot determine the value at compile time, and B2 can determine, so the result is false.
—————————————————— some personal summary, if the wrong place, but also hope that a variety of Bo friends to point out the exchange.
java-Analysis of String