File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String creation question" Watch "String creation question" New topic

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

Joined: Aug 20, 2001
Posts: 1824

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
Ravi Anamalay
Ranch Hand

Joined: Apr 15, 2003
Posts: 38
Thank you both for your prompt responses.
I agree. Here's the link:
subject: String creation question
It's not a secret anymore!