Transferred from: http://www.diybl.com/course/3_program/java/javajs/2007104/75886.html
The string may be an object that appears in any programming language, and there are two most common ways to create and initialize a string object in Java:
String Str=new string ("XXX");
String str= "XXX";
The two seem to be the same, in fact there is a big difference.
The former is the standard method of object creation in Java, and the objects created will be placed directly into the heap, and a new object will be created for each call, and the latter will create an object reference variable str in the stack, and then see if there is "xxx" in the stack, and if not, store "xxx" in the stack. and makes the reference variable str point to it, and if it already has "XXX", direct str to it. This makes full use of the data sharing advantages of the stack, and of course it can be a trap where objects are likely not created, but point to a previously created object, and the new () method guarantees that a new object is created each time.
The following code shows the difference:
Java code
- Public class Main {
- /** *//**
- * @param args the command line arguments
- */
- public static void Main (string[] args) {
- String stra = "abc";
- String StrB = "abc";
- String Straa = new String ("abc");
- String strbb = new String ("abc");
- System.out.println (Stra = = StrB);
- System.out.println (Straa = = STRBB);
- }
- }
Output Result:
True
False
Two ways to initialize string in Java