File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes how many objects are created Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how many objects are created" Watch "how many objects are created" New topic

how many objects are created

Praveen palukuri
Ranch Hand

Joined: Feb 10, 2005
Posts: 65
here is the porblem

String s1 = "aaaaaaaa";
String s2 = s1;

now tell me howmany objects are created.
Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

An assignment question perhaps?

How many do you think are created? Tell us and someone will tell you if you are right.

JavaRanch FAQ HowToAskQuestionsOnJavaRanch
jaspal singh
Ranch Hand

Joined: Sep 15, 2005
Posts: 54
srings are actually immutable, i.e. once allocated memory they cannot be change.and this feature is actually used to share string contents with other s2 can point to s1 and ultimately only one object is created.

infact if we have string s1="hello world";
and s2 as a substring of s1 then to only 1 instance is created.

i hope ur not confused now...or more confused...

Teach me the art of forgetting, for I always remember wat I have forgotten.
Andyjr Robinson

Joined: Oct 12, 2005
Posts: 6
I am happy that in the first example only 1 object is created but I am interested in the later comment that substrings share the same object as the orginal.

I could see why they might as strings are immutable, but would this actually happen or would another object consisting of the substring be created ??
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
I'm a fan of checking out the source code to see what happens,
rather than resorting to idle speculation. Here is some code
from String:

Now the poster's comment "s2 as a substring of s1 then to only 1 instance is created."
is confusing. I certainly don't know what he was trying to say, But if
I let code do the talking:

In this code snippet, that are two distinct string objects (referred to by s1 and s2)
but that share the same char[]. The fact that substring can result in char[] sharing
can either be a good thing or a bad thing. It's good if sharing gains you efficiency,
but what if you've got a big String and all you want to do is refer to a bit of it
and throw away the rest? String sometimes maligned constructor String(String original)
can help. For why it can be useful, check out its source code, too:

There is no emoticon for what I am feeling!
I agree. Here's the link:
subject: how many objects are created
jQuery in Action, 3rd edition