In Java, string and StringBuffer two classes are defined to encapsulate various operations on strings, stored in the Java.lang package, and can be used directly without import.
The creation and initialization of a string object.
1. Initialize directly using string constants:
String S1 = "Hello world!";
Such strings are strictly anonymous objects of the string class, the object name S1 is stored in the stack memory, and the string "Hello world!" Saved in heap memory.
To create a string object by passing a reference S2:
String s2 = S1;
The first time a string is defined, a space is created in the heap memory, and if a new object is used after a direct assignment or a reference pass, and this content already exists, no new heap memory is opened and the existing string content is pointed to.
2. Initialize using the constructor method:
String s3 = new String ("Hello world!");
This approach will open up a second heap of memory space, where a chunk will become garbage and cannot be automated into the pool operation.
The method of manually pooling is provided in the String class: Public String intern ();
New String ("Hello world!"). Intern ();
3. Use the concatenation method:
String S4 = "Hello" + "world!";
Second, the comparison of string content.
1. Call the Equals () method:
String s = "Hello world!" ; = s.equals ("Hello world!");
This method has been mentioned before,equals () compares the contents of a string, it distinguishes the case of a string, and there is a method of ignoring the case: public boolean equalsignorecase ();.
2. Use the comparison operator "= =":
1 String s1 = "Hello world!" ; 2 String s2 = "Hello world!" ; 3 New String ("Hello world! "); 4 Boolean result1 = (S1==S2); // true 5 Boolean result2 = (S1==S3); // false
As you can see,"= =" completes the decision of two object heap memory addresses , comparing whether two objects refer to the same instance, rather than the actual string content comparison.
Once the string is declared, it cannot be changed.
String s = "Hello"= s + "World"= s + "!" ; System.out.println (s); // Hello world!
From the output, the contents of the string are changed, but in fact only the reference to the string object has changed, opening up additional heap memory space, resulting in a lot of string garbage.
Therefore, in the programming process should try to avoid multiple modifications to the string content, so as not to appear a lot of garbage.
Four, the common method of the string class.
In Java, a number of operations are defined in the string class, and some of the common methods are listed below:
Others are no longer described in detail, using only one example to summarize their use:
The String class in Java