Home » Java » [Java] String

[Java] String

interviewed some of the questions String created before, and found the answer was too stupid, still need to study hard under.

String s = "ABC";


string in quotes inside is called string constants in JVM, there is a dedicated storage area constant, file Java at compile time, the compiler will scan all string constants. If there is no constant pool, then in the constant pool in the new one, returns a reference, and will maintain a constant reference there is a constant. The table is stored in the java file and then later met constant, see the constant pool there, if any, directly return a reference, or the new.

 String S1 = "ABC"";
String S2 = "ABC"";
System.out.println (S1 = = S2); the
code is true, point to the constant pool in the constant.

, what if new came out,


 String S1 = "ABC"";
String S2 = new String ("ABC");
System.out.println (S1 = = S2);

Returns false. because the new operation creates a new object, in heap memory, and in a very large pool, a new object is created with just one new operation, but the content is the same as.

what if there is a plus? Need to look at the situation,.

The sum of the constant

of two strings, the compiler looks, the final result is constant, because it can be decided in the compiler. So the sum of constant or constant. But if the object? This is different, the sum of the compiler between objects will explain for the first new of a StringBuffer, and then execute the append method and finally toString. To view the toString source code can be found, the last is to new a string return, so once the object plus participation is different,.

will generate a new object in the final

, public, synchronized, String, toString () {
Return, new, String (value, 0, count);
below is an example:
, String, S1 = "ABC"";
String S2 = "d"";
String S3 = S1 + s2;
String S4 = "ABC" + "d"";
String S5 = "ABCD"";
System.out.println (S3 = S4);
System.out.println (S5 = = S4);

first returns false, second true.

, let's talk about the difference between string, StringBuffer, and StringBuilder.

string is not a variable, plus is realized by StringBuffer (a quantity).Stringbuffer can change, and is thread safe. Then the application of a single thread, the use of StringBuilder is better, because it does not support multi threading, reduces the overhead of the specific application scenarios which have been added. For the operation, with string will repeatedly create objects, the low efficiency of.