|
1. Use the new keyword
string S1 = new String ("AB"); //
2. Use string constants to assign values directly
String s2 = "abc";
3. use the "+" operator for string connections
String s3 = "abc" + "D";
String S4 = s3 + 5; Abcd5
Constant Pool Concepts:
The Java Runtime maintains a string pool, also known as a string buffer . The string pool is used to hold the various strings produced in the runtime, and the contents of the strings in the pool are not duplicated . The normal object does not exist in this buffer pool, and the object created only exists in the stack area of the method.
the creation of a String object is very elaborate, the key is to understand its principle.
principle 1: When using any way to create a string object s ,the Java runtime (the running JVM) will hold this s a String object in the string pool that has the same content, if it does not exist, creates a string s in the pool ,otherwise it is not added to the pool.
principle 2: in Java, whenever you use the new keyword to create an object, you must create a new object (in the heap or stack area).
principle 3: Creating a String object using direct designations or concatenation with a pure string will simply check the string in the maintenance string pool, and no one in the pool will create a , there is it! However, the String object will never be created in the stack area again .
principle 4: Creating a String object with an expression containing a variable will not only examine the maintenance of the string pool, but also create a a String object. finally point to the object in the heap memory
|