aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String creation question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String creation question" Watch "String creation question" New topic
Author

String creation question

Ravi Anamalay
Ranch Hand

Joined: Apr 15, 2003
Posts: 38
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.


with kind regards,<br />Ravi
Joel McNary
Bartender

Joined: Aug 20, 2001
Posts: 1815
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.
Francis Siu
Ranch Hand

Joined: Jan 04, 2003
Posts: 867
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


Francis Siu
SCJP, MCDBA
Ravi Anamalay
Ranch Hand

Joined: Apr 15, 2003
Posts: 38
Thank you both for your prompt responses.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String creation question
 
Similar Threads
Question on strings
doubt in String
.equals()
String creation
Difference between s = "" and new String("a")