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 / General / May 2006

Tip: Looking for answers? Try searching our database.

String Literal Question

Thread view: 
Mayor Curley - 25 May 2006 18:14 GMT
Hi, All:

I need some help on Java as I go through my code to make it more solid.

In this for loop how many String objects are being created?

for(int i = 0; i < 1000000; i++) {
   someMethod("stringX");
}

Now in this for loop how many String objects are being created?

for(int i = 0; i < 1000000; i++) {
   someMethod("stringX");
   someMethod("stringX");
   someMethod("stringX");
   someMethod("stringX");
   someMethod("stringX");
}

Thanks,
Mayor
Alex Hunsley - 25 May 2006 18:29 GMT
> Hi, All:
>
[quoted text clipped - 5 lines]
>     someMethod("stringX");
> }

One string.

> Now in this for loop how many String objects are being created?
>
[quoted text clipped - 5 lines]
>     someMethod("stringX");
> }

One string. The key is that you write "stringX", and not:

new String("stringX")

- as calling new will create a new String object each time you call it.

> Thanks,
> Mayor
Eric Sosman - 25 May 2006 18:59 GMT
Mayor Curley wrote On 05/25/06 13:14,:
> Hi, All:
>
[quoted text clipped - 5 lines]
>     someMethod("stringX");
> }

   (Didn't this question rumble past just a few days ago?)

   The loop creates no String objects at all (unless
someMethod() creates them).

> Now in this for loop how many String objects are being created?
>
[quoted text clipped - 5 lines]
>     someMethod("stringX");
> }

   The loop creates no String objects at all (unless
someMethod() creates them).

   The process of loading the class that contains these
code snippets will create one String object with the value
"stringX" (or will arrange to re-use an existing String
with that value).  The loops then make one million and
five million references to that lone String, but create
nothing new in and of themselves.

   Extra credit: How many String objects are created by

    for (int i = 0;  i < 1000000;  i++)
       someMethod("string" + i);

Signature

Eric.Sosman@sun.com

Chris Smith - 25 May 2006 20:59 GMT
>     Extra credit: How many String objects are created by
>
>     for (int i = 0;  i < 1000000;  i++)
>        someMethod("string" + i);

I'm afraid the answer to your extra credit question is undefined until
you specify some particular interpretation.  Also, are you counting any
String objects that may be created inside the implementation of
StringBuffer or StringBuilder?

Signature

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

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

Eric Sosman - 25 May 2006 21:19 GMT
Chris Smith wrote On 05/25/06 15:59,:

>>    Extra credit: How many String objects are created by
>>
[quoted text clipped - 3 lines]
> I'm afraid the answer to your extra credit question is undefined until
> you specify some particular interpretation.

   (Ponders ...)  I'm failing to discern the undefinedness.
That doesn't mean undefinedness isn't present, just that it's
escaping my eagle eye.

   Perhaps you're worried about what goes on in someMethod()?
I'd intended the same someMethod() that the original poster
used, so whatever his method does ...

> Also, are you counting any
> String objects that may be created inside the implementation of
> StringBuffer or StringBuilder?

   That was "the trick" in what I meant as a bit of a trick
question.  I even considered asking about

    for (int i = 0;  i < 1000000;  i++)
       someMethod("string" + Integer.toString(i));

... but decided that would be too broad a hint.

Signature

Eric.Sosman@sun.com

Chris Smith - 25 May 2006 22:49 GMT
> Chris Smith wrote On 05/25/06 15:59,:
> >
[quoted text clipped - 9 lines]
> That doesn't mean undefinedness isn't present, just that it's
> escaping my eagle eye.

The undefinedness lies in the implementation of StringBuilder or
StringBuffer, and of Integer.toString(int,int).  Put in the silliest
possible way, there is nothing to prevent all of the StringBuffer append
methods from being implemented as:

   public StringBuXXXer append(...)
   {
       new String();
       new String();
       new String();
       new String();
       new String();
       new String();
       new String();
       new String();
       new String();
       new String();

       ...
   }

More plausibly, there's nothing to prevent Integer.toString(int,int)
from being implemented as:

   private static final String[] dec = { "0", "1", "2", "3", "4" };

   public static String toString(int val, int radix)
   {
       if ((radix == 10) && (val >= 0) && (val < dec.length))
       {
           return dec[val];
       }

       ...
   }

Do you see anything to prevent either behavior?

>     Perhaps you're worried about what goes on in someMethod()?

That wasn't my concern.

Signature

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

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

Chris Uppal - 26 May 2006 10:30 GMT
> More plausibly, there's nothing to prevent Integer.toString(int,int)
> from being implemented as: [..]

Nor anything to say whether Intege.toString() is relevant at all.

In point of fact, in Sun's 1.5.0, it is not.  Aside: even
StringBuilder.append(boolean) is "inlined", which strikes me as overdoing it a
bit ;-)

   -- chris
Mayor Curley - 30 May 2006 13:06 GMT
I would *guess* there must be some sort of compiler optimization and
the compiler would not create 1 million objects.
Chris Uppal - 25 May 2006 19:17 GMT
> Now in this for loop how many String objects are being created?
>
[quoted text clipped - 5 lines]
>     someMethod("stringX");
> }

There must be something strange in the air just now.  Only a few days ago a
person (or persons) known as "John and Diane Curley" posted an eerily similar
question to this very group.  You will easily find the resulting thread (with
the correct answer plus some explations) in Google's newsgroup archive[*].  The
thread title was "java compiler and string literals".

The answer, by the way, is zero.

   -- chris

[*] In case you don't know how.  Go to:
       http://groups.google.com/advanced_search
Type
       comp.lang.java.programmer
into the "Group" field (ignoring the crap that Google put there as an example),
and
       "java compiler and string literals"
into the subject field, press "Search", and off you go...
Tony Morris - 26 May 2006 02:15 GMT
> Hi, All:
>
[quoted text clipped - 18 lines]
> Thanks,
> Mayor

No (yes, none - you'll hear otherwise no doubt) String objects are being
created in the for loop.
One String object is created at class load time from the class'
constant_pool.

Signature

Tony Morris
http://tmorris.net/

Roedy Green - 26 May 2006 22:46 GMT
On 25 May 2006 10:14:00 -0700, "Mayor Curley"
<mayorcurley@hotmail.com> wrote, quoted or indirectly quoted someone
who said :

>for(int i = 0; i < 1000000; i++) {
>    someMethod("stringX");
>}

"stringX" is created when the class is loaded. No other Strings are
created unless inside someMethod.  A reference to "stringX" get pushed
to the stack for each call, but is still a reference to the same
literal object.

Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.



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.