Hi All, Could someone please explain the difference between (1) and (2) below ? (1) String s = "abc"; (2) String s = new String("abc"); I'm not sure what the difference is in terms of the number of objects created. Thanks in advance.
I'm sure that this has been discussed before, but I'm too lazy right now to find the link..... Simply put, a lstring iteral always creates/uses a string. That is, "abc" creates one string. Therefore, the new String("abc") creates one string for the "abc" and one string that is initilized to the string "abc" (that is: create the string "abc." Create a new String object and set it to the value of the string "abc.") It is interesting to note that string literals are pooled, so "abc" == "abc" is true, while "abc" == new String("abc") is false.
Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
hi Ravi Let me use some code to demo the different
Use the equals() method to check the reference of Object which is point to the same value or not.So,line 1,2,3 is true. But now,Line 4,5,6 can show the differ Use the operator == to check the reference of Object which is point to the same place or not. String b=new String("abc");//a String c="abc";//b //a, new String() create an object and return the object reference to b,if another variable create the object and with the same content/value,another variable uses differ memory space,so //4 is false //b, without create a object and variable c point to a literal "abc" which use the same memory space if another object point to the same literal "abc",so //6 is true I hope that you may clear now