Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / March 2004

Tip: Looking for answers? Try searching our database.

How many String Objects ?

Thread view: 
lonelyplanet999 - 27 Feb 2004 09:39 GMT
Hi,

In my textbook of java programming, it quoted one example about String
objects as below:

String s1 = "spring ";
String s2 = s1 + "summer ";
s1.concat("fall ");
s2.concat(s1);
s1 += "winter ";
System.out.println(s1 + " " + s2);

The book said that totally eight String objects created as:

"spring ", "summer " (lost), "spring summer ", "fall " (lost), "spring
fall " (lost), "spring summer spring " (lost), "winter " (lost),
"spring winter " (at this point "spring " is lost).

But I counted ten String objects as shown below:

String s1 = "spring ";            -> 1 String object "spring "
String s2 = s1 + "summer ";       -> 2 String objects "summer ",
                                    "spring summer "
s1.concat("fall ");               -> 2 String object "fall ",
                                    "spring fall "
s2.concat(s1);                    -> 1 String object
                                    "spring summer spring "
s1 += "winter ";                  -> 2 String objects "winter ",
                                    "spring winter "
System.out.println(s1 + " " + s2);-> 2 String objects " ",
                                    "spring winter spring summer "

Am I correct ?

Besides, do I count the number of String objects for below code
segment correctly ?

String s3 = new String("");      -> 2 String objects,
                                   1 referenced by s3, one ""
String s4 = new String("");      -> 2 String objects,
                                   1 referenced by s4, one ""
                                   s3, s4 refers to different
                                   String objects, also, the
                                   2 "" objects refer to
                                   different objects
String s5 = new String("String");-> 2 String objects,
                                   1 referenced by s5, one "String"
String s6 = new String("String");-> 2 String objects,
                                   1 referenced by s6, one "String"
String s7 = new String();        -> 1 String object, referenced by s7

Totally 2+2+2+2+1 = 9 String objects created.

:)
Kannan Ekanath - 27 Feb 2004 11:21 GMT
Hi,
you are wrong on certain assumptions,

s1.concat("fall") does not create 2 string objects
It creates one string object for "fall" and uses the already exisiting
string object of s1 and alters s1 to store "spring fall" or whatever.
similarly

s2.concat(s1) does not create any string object coz you do have s1 and
s2 in memory.

So from your count of 10 if you subtract 2 (as shown above), i think
whatever your book guides you is correct ;)
And in the code snippet that you have provided only 5 strings are
created not 9:)
Thanks
Kannan

> Hi,
>
[quoted text clipped - 50 lines]
>
> :)
Jon Skeet - 27 Feb 2004 11:47 GMT
> you are wrong on certain assumptions,
>
> s1.concat("fall") does not create 2 string objects
> It creates one string object for "fall" and uses the already exisiting
> string object of s1 and alters s1 to store "spring fall" or whatever.
> similarly

No it doesn't. Note that s1 isn't a string object - it's a variable
whose value is a string reference. Simply calling s1.concat("fall")
doesn't change the value of s1, and it *also* doesn't change anything
about the string it refers to. Other than creating an extra string
object which is immediately eligible for garbage collection, it's a no-
op. Here's a small program to prove that:

public class Test
{
   static public void main(String[] args)
   {
       String x = "hello";
       x.concat("fall");
       x.concat("wibble");
       x.concat("bar");
       System.out.println (x);
   }
}

Before you run it, guess what the output will be, using the logic
you've shown above. Then run it and see what the output actually is.

> s2.concat(s1) does not create any string object coz you do have s1 and
> s2 in memory.

That doesn't mean it doesn't create any string objects.

Strings are immutable. String.concat will *always* create a new string
unless the passed parameter is of 0 length. The documentation even says
so:

<quote>
If the length of the argument string is 0, then this String object is
returned. Otherwise, a new String object is created, representing a
character sequence that is the concatenation of the character sequence
represented by this String object and the character sequence
represented by the argument string.
</quote>

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

lonelyplanet999 - 06 Mar 2004 07:48 GMT
> public class Test
> {
[quoted text clipped - 11 lines]
> you've shown above. Then run it and see what the output actually is.
>  
It outputs 'hello' alone :)
lonelyplanet999 - 06 Mar 2004 07:37 GMT
> Hi,
> you are wrong on certain assumptions,
[quoted text clipped - 3 lines]
> string object of s1 and alters s1 to store "spring fall" or whatever.
> similarly

Can't agree with your view point. Cos before s1.concat("fall");
s1="spring ", so to execute s1.concat JVM needs to temporarily combine
"spring " & "fall" although this combined string "spring fall"
ultimately got lost. No matter what s1 reference change, string
objects "spring " & "fall" exist cos String objects are immutable. The
argument left is whether JVM will combine "spring " & "fall" if
concat() will not ultimately assign the result to anything.

Same argument for s2.concat(s1); follows. :)

> s2.concat(s1) does not create any string object coz you do have s1 and
> s2 in memory.
[quoted text clipped - 3 lines]
> And in the code snippet that you have provided only 5 strings are
> created not 9:)

You mean the 2 "" objects created in the first 2 lines, the 2 "String"
objects created in the 3rd & 4th lines and empty String object created
in the 5th line ?

> Thanks
> Kannan
Tony Morris - 06 Mar 2004 11:50 GMT
> Hi,
> you are wrong on certain assumptions,
[quoted text clipped - 68 lines]
> >
> > :)

Your advice is false.

Java 2 Language Specification (3.10.5) states:

Each string literal is a reference (?4.3) to an instance (?4.3.1, ?12.5) of
class String (?4.3.3). String objects have a constant value. String
literals-or, more generally, strings that are the values of constant
expressions (?15.28)-are "interned" so as to share unique instances, using
the method String.intern.

A String cannot be changed aka "immutable".

A side note that is purely academic trivia and unrelated to the advice given
above (confusion unintended):

Most people (and the JLS) will agree that the following will always output
"blah" regardless of the implementation of method(String):

String s = "blah";
method(s);
System.out.println(s);

Does anyone care to disagree (as I do) ?
:)

Signature

Tony Morris
(BInfTech, Cert 3 I.T., SCJP[1.4], SCJD)
Software Engineer
(2003 VTR1000F)

Jon Skeet - 27 Feb 2004 11:55 GMT
> In my textbook of java programming, it quoted one example about String
> objects as below:
[quoted text clipped - 27 lines]
>
> Am I correct ?

Yes. The book seems to have ignored the last line, basically.

It's also incorrect (potentially) in saying that "summer " is lost (and
all the other literals): literals are interned, and although there are
strict rules about *exactly* what that means, it usually effectively
means that strings "created by" literals "hang around" for as long as
the JVM does.

> Besides, do I count the number of String objects for below code
> segment correctly ?
>
> String s3 = new String("");      -> 2 String objects,
>                                     1 referenced by s3, one ""

Yes.

> String s4 = new String("");      -> 2 String objects,
>                                     1 referenced by s4, one ""
>                                     s3, s4 refers to different
>                                     String objects, also, the
>                                     2 "" objects refer to
>                                     different objects

No - the two "" references are references to the same object, because
string literals are interned.

> String s5 = new String("String");-> 2 String objects,
>                                     1 referenced by s5, one "String"

Yes.

> String s6 = new String("String");-> 2 String objects,
>                                     1 referenced by s6, one "String"

No, for the same reason as s4. In other words, using the string literal
"String" will only have created one string, despite being used twice.

> String s7 = new String();        -> 1 String object, referenced by s7

Yes.

> Totally 2+2+2+2+1 = 9 String objects created.

No - 7 strings, for the reasons above.

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Chris Smith - 27 Feb 2004 14:31 GMT
> In my textbook of java programming, it quoted one example about String
> objects as below:
[quoted text clipped - 7 lines]
>
> The book said that totally eight String objects created as:

I believe you're right.  10 String objects will be created.

> Besides, do I count the number of String objects for below code
> segment correctly ?

> String s3 = new String("");      -> 2 String objects,
>                                     1 referenced by s3, one ""
[quoted text clipped - 9 lines]
>                                     1 referenced by s6, one "String"
> String s7 = new String();        -> 1 String object, referenced by s7

This is a little trickier.  Using the same String literal several times
will actually reuse the String object that it describes.  Therefore, I
count seven -- the second instance of "" doesn't result in a new String
object, and the second "String" doesn't result in a new String object.

This brings up a piece of unclear terminology here.  It's a little
inaccurate to describe a String literal expression as creating a new
String object.  It really obtains a reference to a String object, which
is created if necessary and at some indeterminate point.  There are a
couple of situations to look out for:

1. If you're counting String objects created to estimate the performance
of some piece of code, you should be aware that the performance impact
(small as it may be) of String object creation may happen at some other
time.  The JVM, for example, may choose to instantiate all of those
String objects the very instant it loads the class.

2. You are guaranteed that if you run this code twice, the second time
through the string literals point to the same Strings as the first time.  
So repeat runs of the code definitely do not create new String objects.  
That's as opposed to "new String" or "a + b", which will create a new
String object each time the code is run.

So there's no clear definition for whether a String literal expression
creates a String object or not.  It might, but there are certainly
situations where it doesn't.  It would be clearer to say that you're
counting the number of String instances that the section of code *uses*.

So what's the big deal about counting String instances anyway?

Signature

www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

lonelyplanet999 - 06 Mar 2004 07:58 GMT
>  
   String s3 = new String("");      -> 2 String objects,
                                       1 referenced by s3, one ""
   String s4 = new String("");      -> 1 String objects, that referenced by s4
                                       the "" duplicates that in previous line
   String s5 = new String("String");-> 2 String objects,
                                       1 referenced by s5, one "String"
   String s6 = new String("String");-> 1 String objects,
                                       1 referenced by s6, string "String"
                                       duplicates that in previous line
  String s7 = new String();         -> 1 String object, referenced by s7

total string objects = 2+1+2+1+1 = 7

> This is a little trickier.  Using the same String literal several times
> will actually reuse the String object that it describes.  Therefore, I
> count seven -- the second instance of "" doesn't result in a new String

You mean above 7 objects ?

> object, and the second "String" doesn't result in a new String object.
>
[quoted text clipped - 5 lines]
>
> So what's the big deal about counting String instances anyway?

It matters when this is an exam question :)


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.