String literal and String Object

P

Prakash Prabhu

Hi,

Is there any performance benefit of using a String literal instead
of creating a new String Object , like , for eg :

String str1 = "Hello I am here "; //String literal

instead of

String str3 = new ("Hello I am here "); //String Object

Don't both str1 and str2 point to objects on the heap , since in Java
most of the binding is done at run time?

Thanks,
Prakash
 
J

Joona I Palaste

E.C. Bäck said:
String are weird objects. As far as I know,
str1 = "Thing"; and
str2 = new String("Thing");
are very different. The former makes one new string object and assigns a
reference to str1. The latter makes a new string object, twice, and assigns
a reference to str2. Strings are immutable; don't make too many of them.

The new operator *ALWAYS* creates a new instance, which takes up space
independently from the other instances, no matter what those instances
are.
If you type:

String[] foo = new String[1000];
for (int i=0; i<1000; i++) foo=new String("Thing");

you are guaranteed to end up with 1000 different String objects. If, on
the other hand, you type:

String[] foo = new String[1000];
for (int i=0; i<1000; i++) foo="Thing";

then depending on the JVM settings, you might end up with only one
String object, being referred to by 1000 references.

--
/-- Joona Palaste ([email protected]) ---------------------------\
| Kingpriest of "The Flying Lemon Tree" G++ FR FW+ M- #108 D+ ADA N+++|
| http://www.helsinki.fi/~palaste W++ B OP+ |
\----------------------------------------- Finland rules! ------------/
"I am not very happy acting pleased whenever prominent scientists overmagnify
intellectual enlightenment."
- Anon
 
?

??????

literal will point to the same object ...
new will create a new object although the word is the same ...
so ... you should use new only you want to ...
 
J

John C. Bollinger

Joona said:
you are guaranteed to end up with 1000 different String objects. If, on
the other hand, you type:

String[] foo = new String[1000];
for (int i=0; i<1000; i++) foo="Thing";

then depending on the JVM settings, you might end up with only one
String object, being referred to by 1000 references.


If you get anything different in this case then your JVM is out of
compliance with the JLS (section 3.10.5).


John Bollinger
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top